C++ work with files | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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();

6th Mar 2019, 4:50 PM
coding-space.ru
coding-space.ru - avatar
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"; }
7th Mar 2019, 7:38 AM
Prokopios Poulimenos
Prokopios Poulimenos - avatar