Hello, I'm a C++ beginner and I have a doubt about bad input, why in this program if I enter the value 2.5 and 3.5 the reading of 3.5 fails ? If I write this program using just one variable it doesn't happen, why ? I have the same problem if I write the same program but using doubles (if I enter two ints, the second reading fails) why ?
1 2 3 4 5 6 7
int a = 10;
int b = 100;
cin >> a >> b;
cout << a << " " << b << "\n";
One feature with cin is that it expects your entry to conform to the variable type you have declared. In the case of int a, a decimal point is undefined in type int, so cin will begin a chase, in which it only ends when you interrupt the program.
I'm not sure about the doubles situation. On my system as long as I input a number it does what it's supposed to do. In this:
1 2 3 4
int a = 10;
int b = 100;
cin >> a >> b;
cout << a << " " << b << "\n";
You can't enter a non-int value when you've declared an int, or cin >> will go into an infinite loop. I don't know enough about the cin command, so I can't say why.
I get the same result whether I put in one variable int a, or two int a, int b. Also have no problems with declaring them as doubles.
You can't enter a non-int value when you've declared an int, or cin >> will go into an infinite loop. I don't know enough about the cin command, so I can't say why.
It does not go into an infinite loop. It is put into an error state. While a stream is in an error state, all read/write operations do nothing. Either clear the error state (which is a nuisance) or don't allow the stream to enter the error state in the first place (as in my example).
Gotcha. It looks infinite on the monitor. . . ! But right usage is right usage, after all. Like I said, I don't know enough about cin, maybe should read up on it more.