When the program encounters this:
cin >> dato;
Try reading an integer from the standard input. If the first character found is a numeric digit or the sign (
- ), the
stream will understand that it can start to extract an integer. When it ends? As you are reading an integer it will end when you can not extract more digits, which happens, depending on your case, when it meets the point. At that moment, stop reading and return in
dato the number read until that moment.
That is, before an input
4.5 , in
4 is stored and in the input buffer the residual
.5 remains. You can check that this is true with the following example:
std::cin >> variable >> cadena;
std::cout << variable << '\n' << cadena << '\n';
Before a type entry
4.5 the program prints the following:
So, as you can see, the program does not do any magic but just gives you what you ask.
We would have a different situation if the conversion were made once the data was read. For example, imagine that instead of reading an integer, read
double and then try to store that number in an integer. Something like this:
std::cin >> temporal;
int dato = static_cast<int>(temporal);
In this case,
cin will read the full number
4.5 and store it in
temporal . The conversion to integer will cause a truncation of decimals, so the decimal part (
.5 ) will be lost and in
dato the whole part will be finally stored (
Where is the difference in both cases? The result stored in
dato does not change, it is the same in both cases, however in this second example the input buffer is clean, without waste.
If we modify the example a bit:
int v1, v2;
std::cin >> v1 >> v2;
std::cout << v1 << '\n' << v2 << '\n';
And you enter, for example,
4.5 6 the program will print the following:
Where does that 0 come from? What happens is that after reading the first integer in the input buffer the following residual remains:
.5 6 . That initial point prevents you from correctly reading a second integer. When the reading error occurs, the error flags of
cin are activated and the stream is blocked until these flags are restarted.
This example shows how important it is to clean the input buffer before reading:
int v1, v2;
if( !(std::cin >> v1) )
std::cin >> v2;
std::cout << v1 << '\n' << v2;
clear method cleans the stream error flags. This action is only executed when the reading of the first integer fails (for example if you enter a character).
ignore method allows you to discard characters from the stream . In this case all characters that are found until the first line break will be discarded.
numeric_limits is a class that allows you to obtain the limit values for each type of data (remember that the ranges are usually dependent on the machine). In this case it gets the highest number that can be stored in a signed integer.