0

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'.

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.