mercredi 25 janvier 2023

While loop in File Handling C++ [duplicate]

#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++

Aucun commentaire:

Enregistrer un commentaire