filereadfile

Reading an input file and the output is not as I expected


My file contains "abcdefg". Why when I use this part of code, in console, it prints letter 'g'?

#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
    
int main () {
  char ch;
  fstream file;
  file.open("myfile.txt", ios::in);
  file.setf(ios::skipws);
  while (1) {
    file >> ch; 
    if (file.fail()) break;
    cout << ch; 
    cout << "\n";
  }
  file.close();
  return 0;
}

I expect to output all chars except letter 'g'.


Solution

  • For me it gives all letters output. It is OK, because when it reads the last letter "g", still the stream is not in a failed state so "g" gets printed. Stream enters failed state when you tried to read something and you could not (reading something after "g"). See fstream::fail() doc and coditions when failbit is set.