Comparing words from two different files using fstream

I'm trying to input a html file and copy everything from that file to a new html file with some changes. I need to read the html file word by word and compare them to a file with some keywords. If a keyword matches a word in the html file then it will add italic tags around that word in the output html file. As it is now it doesn't output anything.

Logically I want to read a word from the html file and then compare it to every keyword and output the result.

fileIn = original html file
keyword = keywords file
outFile = html file writing to


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
std::string str;
	std:: string word;

	while(fileIn.good()){
		fileIn >> str;
		
		while(keywords.good()){
			
			keywords >> word;
			
				if (str.compare(word) == 0){
				outFile << "<i>" << word << "</i>";
				}
	
				else{
				outFile << str << " ";
				}
						
			}
		
		
	}
You try to read the keywords from file every time you read a word from the fileIn. This might work the first word but for the rest keywords.good() will always return false. What you need to do is to read the keywords before the main loop and save them in some data structure. I would recommend a set in this situation. The could would look something like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
    std::set<std::string> keywordsSet;
    std::string word;
    while (keywords >> word) {
        keywordsSet.insert(word);
    }

    std::string str;
    while (fileIn >> str) {
        if (keywordsSet.find(str) != keywordsSet.end()) {
            outFile << "<i>" << str << "</i>";
        } else {
            outFile << str << " ";
        }
    }
Thank you that worked for the most part. The only thing that doesn't work is if the word is directly followed by a punctuation mark. Is there an easy way to fix this for all punctuation or will I need to write several if statements for each type of punctuation?
Topic archived. No new replies allowed.