I'm studying C++ using the book : Programming principles and practice using C++. At the end of chapter 3 the author ask what terminates reading input into an int, I thought that the reading of input into an input terminated when you enter a whitespace just like the string type but after writing this program I have some doubts :
constexpr double cm_per_inch = 2.54;
double lenght = 1;
char unit = 0;
cout << "Please enter a lenght followed by a unit (c or i):\n";
cin >> lenght >> unit;
if (unit == 'i')
cout << lenght << "in == " << cm_per_inch * lenght << "cm\n";
else
cout << lenght << "cm == " << lenght / cm_per_inch << "in\n";
Here if I enter the input 1i cin will read 1 into lenght and i into unit, why ? shouldn't I use a whitespace to terminate reading into an int ? What's wrong ?
The >> operator on cin knows the type of the variable that it is attempting to extract and parse. In your case, cin reads from standard input as long as the bytes extracted continue making up an integer. As soon as any non-integer character is encountered, cin is done reading in the integer. The barriers that determine when parsing is done varies depending on what type of variable you are attempting extract through the >> operator on cin. num_get::get is what the >> operator on cin internally calls to parse variables based on the format expected.
Here is a link to a reference about the >> operator that cin implements (it goes into lots of detail): http://www.cplusplus.com/reference/istream/istream/operator%3E%3E/
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