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

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!
I don't think it does:

Return Value
The function returns *this.

Errors are signaled by modifying the internal state flags
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.
cin.failbit(), cin.eof(), etc
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
You have to clear the stream (to reset the error bits)
cin.getline() doesn't clear the stream like getline() does so as firedraco said, you need to clear it yourself.
The function is cin.fail() rather than cin.failbit(). Or you could do !cin.good().
I'm pretty sure just !cin works too.
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
Topic archived. No new replies allowed.