Skipped cin statement

I understand that there are better ways to validate input than what I have written. I am not trying to fix my code. I just want to understand why the second cin statement is skipped when the first receives a string into a double variable.

Trying to understand what is happening:
userInput is expecting a double, but a string is entered instead. The string is not saved into the variable. No change is made to existing data within userInput. But, then the second cin statement is skipped.

Why?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>

int main()
{
	double inputDouble = 1.0;
	int skippedVar;

	std::cout << "User input: ";
	std::cin >> inputDouble;

	std::cout << "Saved in inputDouble: " << inputDouble;

	// This statement is skipped.
	std::cin >> skippedVar;

	std::cout << std::endl;
}
Last edited on
I ran the program and got weird output but i was able to enter a value into skippedVar
hi @Meden

your code works as expected (or I don't understand your question)

line 9 you are asking user to input number (floating point) then you display entered text on screen. I am guessing that because you don't use endl; to get to the next line or some message to user, you only get ability to type number straight away.

add to the code

std::cout << "I have typed: " << skippedVar << std::endl;


on the other hand if you type not numbers in to first cin then I expect you get a lot of rubbish and this is causing program to crash?
Last edited on
After a formatting error, the stream enters a failed state. Further operations on the stream will fail immediately until the error state is cleared.

http://en.cppreference.com/w/cpp/io/basic_ios/fail
Last edited on
I think maybe you guys are entering in a double rather than a string into the double variable. I think part of the answer to my question is here:
http://www.cplusplus.com/reference/ios/ios/rdstate/

I just have to experiment with it to come up with good examples.

Output:
User input: asdf
Saved in inputDouble: 1
Press any key to continue . . .

Edit:
I didn't see mbozzi's post before I posted mine.
Last edited on
Topic archived. No new replies allowed.