Safeguarding scanf() reads as with cin >>. Is this possible?

1
2
3
4
5
6
7
8
int x;
backhere:cin >> x;
if (cin.fail())
   {
      cin.clear(); cin.ignore(9999, '\n');
      goto backhere; 
   }


Will catch bad input errors, say if a user enters a char instead of a digit.
But
1
2
int x;
scanf("%d", &x);

Will not provide any warnings if the user inputs bad input, and the read will be ignored if say a user enters a char.

How can I make this latter code more robust like the first code?
As a rule of thumb, if you find yourself using "goto" in your C++ code then you are doing something wrong.

I believe the operators on iostream objects are virtualized. You should take the extraction operator attempt to cast the input to the desired data type and if it fails return a null. This way the user can test the input for null instead of this magic "goto-if-then-break" whoi.
You lost me starting with 'virtualized'. Can you provide an example? I'm not sure if I follow you.
Honestly we'd be talking about overloading the primary operator for istream class and it might not have been the best idea for me to jump right at that for a solution in the beginners section.

How about instead of using goto you enter a loop for the user if the fail bit is checked?
If cin failed you can't just use it again - you have to use cin.clear() first.
The C function scanf() returns an integer which is the number of items successfully read.
See http://cplusplus.com/reference/clibrary/cstdio/scanf/

You could do something like:
1
2
3
4
5
int x;
if ( scanf("%d", &x) != 1 )
{
    // Error handling code
}


You probably need to put this in a loop as was also suggest by Computergeek01 for the cin version.

L B is also right though, if the read operation fails the bad character stays in the buffer, you need to clear it before using it again.

How about instead of using goto you enter a loop for the user if the fail bit is checked?


Thats the whole point. Scanf doesn't have a fail bit.
thanks alrededor I will look into it.

Today i've been reading up on stringstreams. Thats not a bit too technical for a beginner is it?
Topic archived. No new replies allowed.