Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does cin do when there is an error

#include<iostream>;

int main()
{
    int a = 1;
    int b = 2;
    std::cin >> a >> b;
    std::cout << a << "+" << b << "=" << a+b << std::endl;
    return 0;
}

when I enter 3 4 as input,the output will be 3+4=7,well,it's strange; But when I enter a b,the output is 0+0=0(Why it is 0 and 0?); The most confusing,a 4,it will be 0+0=0(Why not '0+4=4'?????); Then i write another prog.

#include<iostream>;

int main()
{
    int a = 1;
    int b = 2;
    std::cin >> a;
    std::cin.clear();
    std::cin >> b;
    std::cout << a << "+" << b << "=" << a+b << std::endl;
    return 0;
}

When i enter a 4,why is it still 0+0=0?Shouldn't it be 0+4=4?

Thanks to all the warm-hearted!!

I write prog3,to test what will happen when i don't write int a=1;int b=2;

2

#include <iostream>
using namespace std;
int main()
{  
    int a,b;
    cin >> a  ;
    cin >> b;
    cout<< a << "+"<< b <<"="<< a+b << endl;
    return 0;
}

When a bagain,it outputs 0+-1218170892=-1218170892(Why isn't 0+0=0??)

like image 692
user1668903 Avatar asked Sep 13 '12 14:09

user1668903


People also ask

What does the cin statement do?

The c++ cin statement is an instance of the class iostream and is used to read data from a standard input device, which is usually a keyboard. For reading inputs, the extraction operator(>>) is combined with the object cin.

How do I clear Cin error?

The cin. clear() clears the error flag on cin (so that future I/O operations will work correctly), and then cin. ignore(10000, '\n') skips to the next newline (to ignore anything else on the same line as the non-number so that it does not cause another parse failure).

How does C++ deal with invalid input?

The thing to do is to clear that flag and discard the bad input from the input buffer. See the C++ FAQ for this, and other examples, including adding a minimum and/or maximum into the condition.

Does CIN overwrite?

Every time you read from cin to a variable, the old contents of that variable is overwritten.


2 Answers

Like all istreams, std::cin has error bits. These bits are set when errors occur. For example, you can find the values of the error bits with functions like good(), bad(), eof(), etc. If you read bad input (fail() returns true), use clear() to clear the flags. You will also likely need an ignore(1); to remove the offending character.

See the State functions section for more information. http://en.cppreference.com/w/cpp/io/basic_ios

like image 95
Drise Avatar answered Sep 27 '22 22:09

Drise


The value is set to zero on an error as per C++11: If extraction fails, zero is written to value and failbit is set.

On the 'a 4' example, both values are 0 because the buffer has not been flush/cleared, so the second cin read is still reading the error, and also receives a value of 0.

like image 34
Sogger Avatar answered Sep 28 '22 00:09

Sogger