why when cin is always 0?

Sep 18, 2018 at 3:07pm
in this code,
int k;
cin>>k
if I type not int like 'a' or '\'
they are all recognized as 0 and code is operated strangely
why this happened??
Last edited on Sep 18, 2018 at 3:09pm
Sep 18, 2018 at 3:16pm
When input fails (failed to read an integer), zero is written into the integer k,
and the stream (cin) is put into a failed state.

We can check for successful input with
1
2
3
4
5
6
7
8
9
10
if( std::cin >> k )
{
    // success. use k
    // ...
}
else 
{
    // input failed, k is set to zero.
    // ...
}
Sep 18, 2018 at 3:23pm
@JLBorges
Thanks for your kind advise!
But how can I differentiate (fail case) and (success case but type 0)
k=0 in both cases...
Sep 18, 2018 at 3:49pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>

int main()
{
    int k ;
    std::cout << "enter an integer: " ;

    if( std::cin >> k )
    {
        std::cout << "successful input. the value of k is " << k << '\n' ;
        if( k == 0 ) std::cout << "(the user entered zero)\n" ;
    }
    else
    {
        std::cout << "input failure. the user did not enter an integer\n" ;
    }
}
Topic archived. No new replies allowed.