+ 1
C++ work with files
Why does this code output twice the last row inside my file??? setlocale(LC_ALL, "Russian"); string str; ifstream file("D:\\spacecoding.ru\\input.txt"); ofstream out("D:\\spacecoding.ru\\output.txt"); bool headerUsed = false; while(file){ getline(file, str); cout << str << endl; out << str << "\n"; } file.close();
1 Answer
0
The problem is when getline reads the last line (i.e. it reads until EOF),
while(file) will still evaluate to true, causing the loop to be run again.
Instead, you want something like:
while(getline(file,str)){
cout << str << endl;
out << str << "\n";
}
or
while(!file.eof()){
getline(file,str);
cout << str << endl;
out << str << "\n";
}