reading text file help?
Feb 16, 2012 at 12:57am UTC
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;
}
Feb 16, 2012 at 1:58am UTC
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 Feb 16, 2012 at 1:58am UTC
Feb 16, 2012 at 2:30am UTC
this compiles. but still does not do anything. could this mean that something is wrong with the text file opening?
Feb 16, 2012 at 3:02am UTC
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 Feb 16, 2012 at 3:02am UTC
Topic archived. No new replies allowed.