0

In istream, I use cin.getline() to accept some of the characters and I input the EOF signal(as my OS is MAC, I press control + D) then comes the second cin.getline() to accept the rest of the stream. However, I test the value of cin.eof(),3 times, before the first cin.getline(), between the first and second cin.getline() ,and in the end. And in this program, I all use the EOF signal to terminate this three cin.getline();

the code:

#include<iostream>
using namespace std;
int main()
{
    cout<<"now EOF:"<<cin.eof()<<endl;
    char character[10];
    cout<<"input ten digit character,with '!' in the middle,end with EOF(ctrl+d):"<<endl;
    cin.getline(character, 10,'!');
    cout<<endl;
    cout<<"get the character:"<<endl;
    cout<<character<<endl;
    char character2[10];
    cout<<"now EOF:"<<cin.eof()<<endl;
    cout<<"press(ctrl+d):"<<endl;
    cin.getline(character2, 10,'!');
    //cin>>character2;
    cout<<endl;
    cout<<character2<<endl;
    cout<<"now EOF:"<<cin.eof()<<endl;


}

the result is here:

now EOF:0
input ten digit character,with '!' in the middle,end with EOF(ctrl+d):
123!456

get the character:
123
now EOF:0
press(ctrl+d):

456

now EOF:1

but when I substitute cin.getline(character2, 10,'!') with the commented part cin>>character2 :

the result is:

now EOF:0
input ten digit character,with '!' in the middle,end with EOF(ctrl+d):
123!456

get the character:
123
now EOF:0
press(ctrl+d):

456
now EOF:0

I want to know,why this happen and how the cin.eof() value change. Thank you!

YOUNG
  • 23
  • 1
  • 6

2 Answers2

1

In your second example, the new line character is still available to read - you've read a string, not a line.

See the missing extra newline in the output? That's the clue.

But more importantly, don't use eof. See Why is “while ( !feof (file) )” always wrong?

Community
  • 1
  • 1
Karoly Horvath
  • 94,607
  • 11
  • 117
  • 176
  • Did you mean that in the second example the "cin>> "regard the EOF signal as a string,and do not do anything ? – YOUNG May 06 '16 at 12:48
0

If istream::eof() returns true it means that the previous input operation failed because the stream was at the end of the file. That's why you can't use it to control an input loop: by the time it's true, the input has already failed. And that's why the input operations themselves can tell you whether they succeeded: that way you can loop as long as the input succeeds. This code

while (cin.getline(whatever)) {
    do_something(whatever);
}

will execute the loop each time the getline call reads a line. When cin reaches the end of the input, the getline call will fail, and the loop won't be executed. This code:

while (!cin.eof()) {
    cin.getline(whatever);
    do_something(whatever);
}

will call do_something even if the call to getline fails. After that call fails, on the next time through the loop, cin.eof() will return true and the loop will exit.

Pete Becker
  • 74,985
  • 8
  • 76
  • 165