petat_irrumator
petat_irrumator

Reputation: 11

Cin causes the value of a variable to change unexpectedly

So I am following this book Programming: Principles and Practice Using C++ 3rd edition and in section 2.3 Author gives the following code:

cout << "Please enter your first name and age\n";
string first_name = "???";
int age = -1;

cin >> first_name >> age;
cout << "Hello, " << first_name << " (age " << age << ")\n";

According to the book If i give the following input: 22 Carlos Then the value of variables become first_name="22" and age=-1. Age retains it's original value because cin did not succeed in putting Carlos to int variable age.

Now if I run the above code and give the same input 22 Carlos on my machine then the value of variables are first_name="22" and age=0. I tried putting the code in an online compiler and running it there, but I still get the same result. So, why does the value of age changes to 0? The full code is as follows:

#include <iostream>
using namespace std;
int main()
{
cout << "Please enter your first name and age\n";
string first_name = "???";
int age = -1;

cin >> first_name >> age;
cout << "Hello, " << first_name << " (age " << age << ")\n";

system("pause");
return 0;
}

Upvotes: 0

Views: 27

Answers (0)

Related Questions