I have question about ifstream!!!

Hi, I have question about the ifstream!!!
I am taking algorithm class right now and have one project that sort words from large size text file. So in my program I am using ofstream and ifstream to open and write words in sorted order..!!! but I am having one issue!!
I am trying to read text file as following!!
1
2
3
4
5
6
7
8
9
ifstream infile;
ofstream outfile;
infile.open("some_text.txt");
outfile.open("some_output.txt");
string temp;
while(!infile.eof()){
     infile >> temp;
     outfile << temp;
}

Let's say some_text.txt has five words in it...aaa bbb ccc ddd eee
If I read each words like the way above, the last word repeat one more time.
I get the some_output.txt with words aaa bbb ccc ddd eee eee
So I tried following code!!
1
2
3
4
5
6
7
8
9
10
ifstream infile;
ofstream outfile;
infile.open("some_text.txt");
outfile.open("some_output.txt");
string temp;
while(!infile.eof()){
     infile >> temp;
     if(infile.eof()) break;
     outfile << temp;
}

For some text file, this code seems works...!
But the thing is it does not repeat sometimes...
Anyone know why?? And how to fix it??
A suggestion, change this:
1
2
3
4
while(!infile.eof()){
     infile >> temp;
     outfile << temp;
}

to this:
1
2
3
while (infile >> temp) {
     outfile << temp;
}


But the thing is it does not repeat sometimes...
It depends whether there is anything (such as a blank line) after the last word or not. That's because infile >> temp; will read a word and stop when it reaches any whitespace or the end of the file. So eof is not set because it didn't reach the end of file. The next time around, it will ignore any leading whitespace, until it finds the first character of a word. But instead it just reaches the end of file. It's best to avoid testing eof and just test that the infile operation was successful.
Last edited on
Thank you very much!! It seems work correctly now!!! thanks a lot!!
Topic archived. No new replies allowed.