hanie
hanie

Reputation: 1885

checking success of taking input

I'm new to C++. I had some knowledge of C ,and I know shouldn't assume C rules are same as C++. I'm just looking for some same solution.

for example In C when we use:

int a;
if (scanf ("%d", &a) != 1);

to check if an valid value entered .For example if instead of a integer ,a char was taken as input this will tell us scanf failed to take an integer as input.

but in C++ I debugged this code when I gave input m to program:

    int a;
    cin >> a;

and it assigned 0 to a ,but I did same thing with scanf and value of a was -858993460.(while default value of a in both langues was -858993460)

so here is my problem , How can I know if cin failed to take valid input? and is it usual that , 0 is assigned to a in C++ code? and if it's usual how can I know entered data was really 0 or was a failure result? is there a way for checking success of cin?

PS: sorry if the question is stupid. I'm competently new to c++.

Upvotes: 0

Views: 925

Answers (1)

srilakshmikanthanp
srilakshmikanthanp

Reputation: 2399

You can check this by good() function like

#include <iostream>

using namespace std;

int main()
{
     int i=0;

     if( ! ( (cin>>i).good() ) )
        cout<<"Error";
     else
        cout<<i;

     return 0;
}

See below:

cin returns reference to it and istream (cin is a object of istream) contains a function good() return true if the stream is in good state otherwise return false.

Upvotes: 1

Related Questions