Cin input only number

Hello,

I am working on an assignment and when executing my code I broke the program when I typed in a letter instead of a number. After doing some looking around, I "sort of" fixed it, but now it created another problem for me. Now it tells me invalid if I type in a letter, but once I type in a number it doesn't recognize it until I put in something invalid and then put in a number.

Overall I just want it to only accept numbers (0+) and tell me invalid and try again if its not. I'll post the snippet I'm talking about. I can post the whole thing if needed but its messy right now till I get it all figured out.

1
2
3
4
5
6
7
8
 cout << "What is the price of your item? (i.e 2.25) " << endl;
	cin >> itemPrice;
	while (!(cin >> itemPrice))
	{
		cin.clear();
		cin.ignore(1000, '\n');
		cout << "Invalid input. Try again. " << endl;
	}


Thank you for any assistance.
The way I do it is kinda costly, first i input the value to a char or string, then check if its a number using isdigit(), if any non number not found, then convert that variable to int
Remove one of the cin statements.
1
2
3
4
5
6
7
 cout << "What is the price of your item? (i.e 2.25) " << endl;
	while (!(cin >> itemPrice))
	{
		cin.clear();
		cin.ignore(1000, '\n');
		cout << "Invalid input. Try again. " << endl;
	}
@Yanson

Thank you! That fixed it for me! Just removing the first cin did it. Thank you again!

Topic archived. No new replies allowed.