Reading From Files

Hello, If I have a file that has a bunch of words in it and some of those words are repeated, how do you grab the first word and then check it with all the other words to see if it is the same. This is what I have so far which is only grabbing the first word twice, saying it is the same obviously, and outputing it.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <iostream>
#include <fstream>					
#include <string>
using namespace std;

int main()
{
	string filename;
	ifstream Line("KeyWordsOnLineHelp.txt");

	if (Line.fail())				
	{
		cout << "Error: main(): Failed to open the file: ";
		cout << "KeyWordsOnLineHelp.txt" << endl;
	}
	else
	{
		while(!Line.eof())
		{
			string word1;
			string word2;
			getline(Line,word1);
			if (!Line.eof())
			{
				bool Found = false;
				while(!Line.eof() && !Found)
				{
					getline(Line,word2);
					if (!Line.eof())
					{
						if(word1 == word2)
						{
							Found = true;
						}
					}
				}
				if(Found = true)
				{
					cout <<      word1    << endl;
				}
			}
		}
		cout << endl;
	}
	cout << endl;
	system("pause");
	return 0;
}
Read them all into memory and do the comparison there unless the file is too large to fit in memory.
The std::map is usually what you'll want. It will accept a string as a key, which will be the word that you read in. If the string doesn't exist, then it gets created automatically. Otherwise, the duplicate word that you read in will overwrite the old (which doesn't really matter, since the values are identical anyway).

Notice that this will not necessarily print out the resulting words in the same order in which they were read in, although that can be left up as an exercise you can implement.
Topic archived. No new replies allowed.