reading text file help?

here is my code, there are around 45,000 words in the text file, it doenst work quite right.

ive also included the txt file im using in the attachments

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

 #include <fstream>
#include <iostream>
    #include <string>
    #include <vector>

    using namespace std;

    int main()
    {
        vector<string> words;
        ifstream file("words.txt");

		
		for (int i = 0; i <=file.eof();i++)
        {
			string word;
			file>> word;
			cout<<word<<endl;
            words.push_back(word);
				cout<<".";//to test... it only prints . once
        }
		cout<<"@@@@MAIN@@@@@"<<endl;



		cin.get();
		return 0;
    }
I am not sure what you think this does:
 
for (int i = 0; i <=file.eof();i++)

But it is almost certainly not what you want.

Try this:
1
2
3
4
5
std::string word;
while(file >> word)
{
    words.push_back(word)
}
Last edited on
this compiles. but still does not do anything. could this mean that something is wrong with the text file opening?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
 
vector<string> words;
string word;

fstream file("words.txt");

while(file >> word)
{
	words.push_back(word); 
}

for(int i = 0; i < words.size(); i++)
{
	cout << words[i] << endl;  // Prints out each word stored in the vector 
}


Have you tried doing it like this? It works correctly for me.
Last edited on
Topic archived. No new replies allowed.