I am curious why cin
behaves in the following way. I think I might have
some misunderstanding about its behavior.
Consider this simple code. This code is asks for some input to be entered, all of which is printed out in the last statement.
#include <iostream>
#include <string>
using namespace std;
int main(int argc, char** argv) {
cout << "Please enter your input: " ;
int a=3, b=87; // initialized to some random integers
string s = "Mary" ; // initialized to a random string
cin >> a ;
cin >> b ;
getline(cin,s);
cout << "You entered the following " << a << " " << b << " " << s << endl;
return 0;
}
Now if the input is 12 34 cat
the output is 12 34 cat
This is expected.
However if the input is cat 23 dog
the output is 0 87 Mary
.
Here is why I think this is unexpected:
cin >> a
should fail since cat
cannot be converted into an integer. However, a
gets replaced with what I presume is a garbage value.
Now since the second number of the input is an integer 23, cin >> b
must succeed. Yet this operation seems to fail, and b
continues to retain its original value unlike what happened to a
.
Similarly getline
fails to place the string <space>dog
into the string s
which continues to retain its original value of Mary
.
My questions are the following.
Does the failure of some
cin
operation mandate the failure of all subsequentcin
operations using the>>
operator or thegetline
function.Why did the failure of the first
cin
operation change the value ofa
whereas the initial values ofb
ands
were unchanged?