Hi:
Assume that the content of the file textfile.txt is:
Have a good day.
Hello world.
I use the following code to access the file textfile.txt:
#include <iostream>
#include <fstream>
#include <string>
int main(){
ifstream infile ("textfile.txt", ios::in)
string s1, s2, s3, s4;
string s;
infile>>s1>>s2>>s3>>s4;//LINE0
getline(infile,s); //LINE1
cout<<"s1:"<<s1<<" s2:"<<s2<<" s3:"<<s3<<" s4:"<<s4<<endl;//LINE2
cout<<"s:"<<s<<endl; //LINE3
}
The output of LINE2 is correct. But the output of LINE3 is a blank
line, not "Hello world." Why?
My thought is that at the end of the string "Have a good day.", there
is a newline character, so LINE1 read the newline character, other than
the string
"Hello world.". Am I right?
If I still want to use LINE0, how to prevent the above problem?
Another question is about the eof() function.
When I use the following code to read a file:
while(!infile.eof()){
getline(infile,s);
cout<<s<<endl;//LINE4
}
I found that after the content of the file is printed, LINE4 always
outputs extra blank lines. It seems to me that the eof() function can
not find the correct end of a file. Why?
Thanks a lot.