1
ifstream fin;
ofstream fout;
char ch;
string st;

fin.open("testfile.txt");
fout.open("testfile.txt");
while(!fin.eof())
{
   fin.get(ch);
    cout << ch;
}
fin.clear();
fin.seekg(ios::beg);
while(!fin.eof())
{
   getline(fin, st);
    cout << st;
}

Test file contains the following:

abcd  efg

1234  hij

result:

abcd efg

1234 hijabcd  efg1234  hij

What I am asking is:

Why are the results different between reading with fin.get(ch) and getline(fin, st)?

Brent Bradburn
  • 40,766
  • 12
  • 126
  • 136
Kisung Tae
  • 75
  • 1
  • 3
  • 1
    `while(!fin.eof())` is broken... use `while (fin.get(ch)) ...` and `while (getline(fin, st)) ...`. See [here](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) for explanation. – Tony Delroy Apr 22 '16 at 02:56

2 Answers2

3

get() returns every character. getline() throws away the line terminator.

user207421
  • 289,834
  • 37
  • 266
  • 440
0

Because your while(!fin.eof()) was broken (see my comment under the question), when you're actually at the end of file you attempt another input operation, and the EOF is then set on the stream but not checked until after the variable you tried to input to has been used.

That's why you print st twice for the last line:

1234 hijabcd  efg1234  hij

getline() does remove the (newline) delimiter from the values set in st, which is why all your output will appear on the same line.

For the get version the attempted read at EOF returns Traits::eof() which you print... that may or may not visibly display something, depending on the eof() value your implementation chooses and your terminal/console program.

Tony Delroy
  • 94,554
  • 11
  • 158
  • 229