Starting C++ learning: integer initialized to -1 return 0

Hi everyone,
I began to learn C++ from Stroustrup book, and I already have a little problem with one of the first programs:

int main()
{
cout << "Please enter your first name and age:\n";
string first_name = "???"; // variable pour une chaine
int age = -1; // variable pour un entier
cin >> first_name >> age;
cout << "Hello, " << first_name << " (age " << age <<")!\n";
return 0;
}

Here, age should keep its initial value (-1) if the user put a wrong type, like 22 Carlos (first_name become "22", but Carlos isn't an integer).
My problem is that if I type 22 Carlos, first_name get 22 but age become 0 instead of -1... Any idea? I use Code::Blocks on Linux.
I have just compiled it with Visual Studio, I entered 22 as first_name, and Carlos as age, and age was -1 at the end, so....

because first_name is a string, when you enter 22 it is actually the string "22".
age is a int.
Maybe the compiler you were using with Code::Blocks sets the int variable to zero when you attempt to assign invalid data to it, while in VS the compiler keeps the original value.
Topic archived. No new replies allowed.