You are trying to read different types of values using cin.
istream
overload the >>
operator to match the type of data you are expecting from input, and cin
is a instance of the istream
class.
When the expected type is an integer, it will consume character up to a string which can be converted to an integer, and leave the remaining characters in the stream for later parsing. The same happens with a float value, or with other simple types.
See this reference page for more details on the operator and the types it supports out of the box.
The bottom line is that if you want to have an integer value, but are expecting a float value from input, you must use the correct type of value you want to parse from input (here float), and do any needed conversion later on (here use trunc
, floor
, ceil
or whichever rounding function that match your needs).
Here's a simple example:
#include <iostream>
#include <string>
using namespace std;
int main() {
float f;
string str;
cout << "please enter a float :";
cin >> f;
cout << "value entered : " << f << endl;
cout << "stream error : "
<< (cin.fail() ? "yes" : "no")
<< endl;
cin >> str;
cout << "remaining data : " << str << endl;
}
This very simple program demonstrate the use of the >>
operator on istream, specifically with an expected float value. For the following input: "1.2345Z6789" (note the Z in the middle of the number), the program will parse the value "1.2345" and have "Z6789" remaining in the input buffer, available for a subsequent read.
If you replace the type of f
from float
to int
, the program, on the same input, would read the value "1", and have ".2345Z6789" remaining in the input buffer.
Note: In your code, you are using the !
operator to test the state of the stream, which is equivalent to the fail
method, which I used in my example.
input
. – Iskar Jarak Nov 13 '12 at 22:472
and leaves.5
for the next input operation to read. – Barmar Nov 13 '12 at 22:48istringstream
if necessary). – Matteo Italia Nov 13 '12 at 22:48cin >> int_variable
works. I'd recommend reading a string and usingboost::lexical_cast
to circumvent it. – chris Nov 13 '12 at 22:49