Why is the last letter being printed twice? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Why is the last letter being printed twice?

#include<iostream> #include<fstream> #include<cstring> using namespace std; int main() { fstream file; file.open("output.txt", ios::in | ios::out); // outputing and inputing in file stream string str="The person answering this is cool"; // l is being printed twice for(int i=0; i<str.length(); i++) //loop that adds str-message into the file (output.txt) characterwise. file.put(str[i]); char ch; file.seekg(0); //file pointer to move back the input pointer to start while(!file.eof()) { file.get(ch); cout<<ch; //this is the loop that is printing it twice } }

30th Jul 2020, 10:21 AM
Prashant Pant
Prashant Pant - avatar
3 Answers
+ 7
It is because eof() returns true only after you read the end of the stream not whether the next read will be the end of the stream. Once it gets to the last 'l' it will simply read it the first time and since it's not the end of the stream the eof flag will not be set. Because of that file.eof() will return false so the loop is ran again. Now get will read the end of the stream so the eof flag is set, ch will remain unmodified and then you print it again. Now that the eof flag is set the loop finally breaks. A better way to read from a file in a loop is to use while( file >> ch ) instead because it both reads and checks for success at once. But I realize that this is commonly taught this way in India and you may be stuck with it so you might want to at least put file.get( ch ) in an if statement before you print anything to check if it succeeded.
30th Jul 2020, 10:47 AM
Dennis
Dennis - avatar
+ 7
Prashant Pant Alternatively you can do the check for eof immediately after calling get .I.e. while(true) { file.get(ch); if(file.eof())break; cout<<ch; }
30th Jul 2020, 12:07 PM
Anthony Maina
Anthony Maina - avatar
+ 6
That's because at the time when your loop is reading and printing last character ('l' in this case), end of file is still not reached. By defination End of file is detected by failing an input operation. So the loop condition will still be true and it will run one more time, but this time input operation will fail as there is nothing to input and last value of "ch" is displayed. Here is the simple fix👇 while( file.get(ch) ) std::cout << ch ;
30th Jul 2020, 10:50 AM
Arsenic
Arsenic - avatar