First of all that "Press [the] any key..." text comes from your IDE, not the program.
Now: the reason your "78.7" input got treaty as 78 and didn't error out is because of the nature of the
cin >> ...
operation. Even though the statement doesn't begin to parse the entered text until you hit enter, this doesn't mean it reads the whole line (ie. all of the text you typed.) In the case of
string
or
char*
, the read will stop parsing at the first white space (ignoring leading white space.) To show this, try the following test program:
1 2 3 4 5 6 7 8 9 10
|
#include <iostream>
#include <string>
using namespace std;
int main() {
string a, b, c;
cin >> a >> b >> c;
cout << "a is \"" << a << "\"\nb is \"" << b << "\"\nand c is \"" << c << "\"\n";
return 0;
}
|
Run this program and and enter the text
Hello, world! My name is whitenite1. |
You should get back
a is "Hello,"
b is "world!"
and c is "My" |
As you see, not only are only the first three words gather from the stream, but you only need to hit enter one time. Now in the case of my
cin >> ...//into an int
the parsing stops at the first non-number (although it will allow a leading minus ('-') sign.) So it stops at your '.' character and just parses "78" which stores the int 78 into total. The remaining ".7" and linebreak are left in the stream.
If you wanted a more thorough error check you could parse the whole line with the function
getline( cin, ... ); //as opposed to cin >> ...
included in the
<string>
header file. Then you could manually parse the whole line to check if it is indeed an integer and nothing else (where the "..." is a C++ string.)