|
-
March 29th, 2009, 12:22 PM
#1
Inifinite loop problem (easy question)
Hey all, sorry for all the beginner's questions 
Anyways, I'm trying to build a simple loop that will protect against unwanted input (i.e. when the user enters a characters instead of an integer). Here's what I have so far:
Code:
#include <iostream>
#include <cctype>
using namespace std;
int main()
{
cout << "Enter a number: ";
int number;
cin >> number;
while (!isdigit(number)) //Created an infinite loop!
{cout << endl << "That is not a number, please try again: ";
cin >> number;}
cout << endl << "Enter a character: ";
char ch;
cin >> ch;
cout << endl << number << " " << ch;
int wait;
cin >> wait;
return 0;
}
First of all, am I correct that (!isdigit(number)) is really saying "Do this while the input is not an integer?"
Whenever I input a numeric value, say 3, I get the message stating "That is not a number, please try again"??!
Whenever I input a character value, I get an infinite loop stating" "That is not a number, please try again", and the program ignores the cin >> number within the loop.
Can anyone tell me whats wrong here?
Thanks.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|