2

At the below code, when I execute non-commented part result is "10**20**30**40**"

But when I execute commented line, output is "10**20**30**40**40**"

I think it's related to eof(), but I cannot know why exactly.

What characteristic does the eof() have??0

input.txt has '10 20 30 40 '

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

int main()
{
    ifstream fin1;
    string s;
    fin1.open("input.txt");
    while (true) {
        fin1 >> s;
        if (fin1.eof()) break; // Q: why calling eof here?
        cout << s << "**";
    }

    // The following is wrong. Why?
    // while (!fin1.eof()) {
    //     fin1 >> s;
    //     cout << s << "**";
    // }

    fin1.close();
    cout << "\n";

    return 0;
}
jtbandes
  • 104,858
  • 34
  • 217
  • 242
ChangHyeon
  • 51
  • 3

0 Answers0