PDA

View Full Version : C++ coding help



harrylmh
April 9th, 2001, 09:49
Hello,
anyone who knows C++ pls help me with this problem:
I want to make a user enter a int value between 1 to 2. Anything more or less, or say the user enters a char type value, and the program will ask for the input again. If I enter a char into the input, it would cause an infinite loop without the "!cin>>num" but with it, the program will freeze. How do I get the program to take the error correctly? How do I get the program to ask for input again if there's a char input and not loop infinitely?

// program start
void main(){
int num
cin >> num;

while (!cin >> num || num<1 || num>2)
{
cin >> num;
}
// program end

}


Thank you!

jw
April 9th, 2001, 15:13
looks like you are using a different compiler than microsoft visual c++, but it should work basically the same.

// program start
void main(){
int num

do {
cout<<"Enter a 1 or 2: ";
cin>>num;
} while (num<1||num>2);

}

not sure about the char which is what you were really asking, but heh the do...while is more efficient.

harrylmh
April 9th, 2001, 23:00
Okay, now using the codes you gave me, try entering an alphabet, say "v". Out-of-the-range numbers are ok, but with letters, you'll see that it'll cause your programs to loop infinitely.

That's the problem, how do I solve that? Anyone know?
PS: The thing is this problem can be actually solved very easily with an expression but is it..? hmmm.

Thanks.

Epgs
April 10th, 2001, 21:09
what i say is trahs the entire thing and start over, jk, try a chat room like at webcrawler.com there are a lot of smart people there