0
#include<iostream>
#include<fstream>
using namespace std;

int main() {

    ofstream f_out;
    f_out.open("file.txt");
    f_out<<"Hello!";
    f_out.close();

    ifstream f_in;
    f_in.open("file.txt");
   
    char ch;

    while(!f_in.eof()) {

        cout<<ch;
        f_in>>ch;
    }
    
    f_in.close();

    return 0;
}
while(!f_in.eof()) {

        cout<<ch;
        f_in>>ch;
    }

I have a problem in the above while loop specifically.

In the above code, inside the while loop why is cout statement before f_in statement. Usually, the cin statement comes before cout, but here its the other way round. If i write f_in first then cout then the program gives wrong o/p as Hello!!, instead of Hello!. Can anyone explain it to me in simple language why the above code is correct & my line of thought is incorrect. Thanks in advance. I am new to learning C++

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
A S
  • 1
  • 1
  • `Can anyone explain it to me in simple language why the above code is correct & my line of thought is incorrect.` Well its wrong both ways. looping while not EOF is always bad. – tkausl Jan 25 '23 at 07:31
  • The above code is not correct. The variable `ch` is being used without being initialised. Where did you get the code from? – john Jan 25 '23 at 07:51
  • And as pointed out in the duplicate the use of `eof` is also incorrect, although of the two errors this is the less serious one. – john Jan 25 '23 at 07:53
  • The correct code is `while (f_in >> ch) cout << ch;` – john Jan 25 '23 at 07:55
  • @john I got the code from a YT video. Can you please clarify why using !eof is bad practice? – A S Jan 25 '23 at 08:01
  • @AS Because it's being used by somebody who doesn't understand what it does. The correct use of `eof` is to test if the **last** input operation failed because of an end of file. But in the code you quoted the programmer clearly thinks that `eof` will tell you if the **next** input operation would fail because of end of file. In other words `eof` tells you what has happened in the past, not what will happen in the future. This is an incredibly common beginner misunderstanding, which gets repeated and repeated by low quality YT videos among others. – john Jan 25 '23 at 08:10
  • @AS To learn C++ effectively you really need a [good book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282) – john Jan 25 '23 at 08:11

0 Answers0