I'm working through Bjarne Stroustrup's Programming - Principles and Practice Using C++ and came to the following example:
#include "std_lib_facilities.h"
int main() {
/* Name and Age input */
cout << "Please enter your first name and age\n";
string first_name = "???";
int age = -1.0;
cin >> first_name >> age;
cout << "Hello," << first_name << "(age " << (age * 12) << " months)\n";
return 0;
}
If you run the program and input Carlos 22, it will correctly output Hello, Carlos (age 22)
. However, if you put in 22 Carlos, he says that the output should be Hello, 22 (age -1)
because since "Carlos isn't an integer... it will not be read". However, when I run it, it returns Hello, 22 (age 0)
which seems like it's assigning a garbage value to it. I'm curious as to why this is happening, as the book implies that unless you input an integer, it won't try to assign anything to the age
variable. I ran the code with breakpoints and confirmed the value of age
changes from -1 to 0 once the non-integer input has been entered.
Am I doing something wrong? Or is this an oddity due to the fact I'm building it through Xcode and whatever compiler comes included with that?
Inputting a string You can use cin but the cin object will skip any leading white space (spaces, tabs, line breaks), then start reading when it comes to the first non-whitespace character and then stop reading when it comes to the next white space. In other words, it only reads in one word at a time.
Every time you read from cin to a variable, the old contents of that variable is overwritten.
The usage of cin is simple, too, and as cin is used for input, it is accompanied by the variable you want to be storing the input data in: std::cin >> Variable; Thus, cin is followed by the extraction operator >> (extracts data from the input stream), which is followed by the variable where the data needs to be stored.
If you follow the trail of calls from the call
cin >> age;
you end up with a call to std::strtol
. The return value of strtol
is:
- If no conversion can be performed, 0 is returned.
Check the status of cin
after the calls to make sure that all the extractions were successful.
cin >> first_name >> age;
if ( cin )
{
// Extraction was successful.
// Use the data.
}
else
{
// Extraction was not successful.
// Deal with the error.
}
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