I have a problem about cin.
int main(void)
{
int a;
float b;
cin >> a >> b;
}
When I give a floating number (such as 3.14) as input, neither a nor b get the complete value (3.14): the output is a=3, b=0.14.
I know that cin will split the input by space, tab or Return, but ‘dot’ will not, right?
And why will the following code work?
int main(void)
{
int i=0;
int k=0;
float j=0;
cin >> i >> k >> j; // i =3, j=k=0
}
And one more problem, what benefit will compiler do this for us?
Thanks!
The formatted input functions work quite simple:
std::ios_base::failbit. If reading fails the input shouldn’t change the variable attempted to be read (the standard input operators follow this rule but user defined input operator might not).The first value you try to read is an
int. Reading anintmeans that a optional leading sign is read followed by a sequence of digits (where, depending on your settings and the value given, the stream may read octal or hexadecimal numbers rather than decimal ones). That is, theintreceives the value3and reading stops right in front of the..Depending on what you read next, the next read fails or doesn’t:
.is found which isn’t a valid part of anintand reading fails.After attempting to read a value, you should always try if the read operation was successful and report potential errors:
Note, that after a failed read you may need to clean up as well, e.g., using
This first clears the error flags (without this, the stream would ignore any further attempts to read the data) and then it ignores the next character.