How to find out what cin.getline() returns?

Sep 20, 2009 at 4:22am
Okay, so I have this line of code
 
cin.getline(var.line1,50);


The rest of the code doesn't matter.

I know that getline() returns either eofbit, failbit, or badbit. My question is how do I find out what is returned. I can't find anything about this on Google/Bing Search.

Thanks!
Sep 20, 2009 at 5:04am
I don't think it does:

Return Value
The function returns *this.

Errors are signaled by modifying the internal state flags
Sep 20, 2009 at 5:38am
Errors are signaled by modifying the internal state flags


So can I get the internal state flags then?

What I want to do, is make sure the user doesn't enter a string too long. Which means I need to be able to detect if there is a failbit.
Sep 20, 2009 at 5:39am
cin.failbit(), cin.eof(), etc
Sep 20, 2009 at 5:52am
Thanks! That gets me into the loop. Now I face a continuous loop

1
2
3
4
5
cin.getline(var.line1,50);
while(cin.failbit){
    cout<<"Error: Your line is too long.\nPlease enter a shorter line: ";
    cin.getline(var.line1,50);
}


That there, I enter a string too long on the first time, and after that, the while loop repeats infinitely. Any clues why?

Note: If I put cin.failbit() rather then cin.failbit I get an error.
Last edited on Sep 20, 2009 at 5:52am
Sep 20, 2009 at 5:55am
You have to clear the stream (to reset the error bits)
Sep 20, 2009 at 6:21pm
cin.getline() doesn't clear the stream like getline() does so as firedraco said, you need to clear it yourself.
Sep 20, 2009 at 6:55pm
The function is cin.fail() rather than cin.failbit(). Or you could do !cin.good().
Sep 20, 2009 at 8:53pm
I'm pretty sure just !cin works too.
Sep 21, 2009 at 1:02am
You have to clear the stream (to reset the error bits)

Thank you, used cin.clear(ios::goodbit);

cin.getline() doesn't clear the stream like getline() does so as firedraco said, you need to clear it yourself.


How do you use getline() alone? I get an error if I remove the cin.

The function is cin.fail() rather than cin.failbit(). Or you could do !cin.good().

Ahh, well that helps! Much shorter then cin.rdstate()==ios::failbit
Don't want to use !cin.good() because I don't want to display for the user to enter a shorter line if it is a fatal error, but good to know!


Overall, here is the full while statement. Plus the first cin.getline()

1
2
3
4
5
6
7
cin.getline(var.line1,50);
while(cin.fail()){
  cout<<"Error: Your line is too long.\nPlease enter a shorter line: ";
  cin.clear(ios::goodbit);
  cin.ignore(99,'\n');
  cin.getline(var.line1,50);
}


Note: For future people reading this, you can also use cin.clear(cin.good()), which is 2 characters shorter. :)

Thanks a lot for your help!
Last edited on Sep 21, 2009 at 1:06am
Topic archived. No new replies allowed.