#include <iostream>
using namespace std;
int main()
{
cout << "Please enter your name and age\n";
string first_name;
int age;
cin >> first_name;
cin >> age;
cout << "Hello, " << first_name << " (age " << age << ")!\n";
}
If I type in Carlos
for age
or any other string I get a 0
. How does this work(why)?
Not sure why the question got down/close votes as it's clearly stated and not broad (and judging by the comments, many people don't know the answer)...
Anyway, for the code:
int age;
cin >> age;
if the input stream did not contain any digits, then the stream is put into a fail state and age
is set to 0
. The characters in the input stream remain there; they can be read by a future read operation once the fail state is cleared.
The behaviour of operator>>
is summarized on cppreference , the full description in the standard is somewhat complicated.
Note: This changed in C++11; commentors reporting garbage output are either running compilers in pre-C++11 mode, or bugged ones.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With