quick question (hopefully) about char and an infinite loop

I'm not going to post any code (unless it's requested) because I think someone with alittle more C++ knowledge then myself could probably answer this quickly.

I'm building a program, and I coded it to where it prompts the user for the input and regardless it'll trigger the while statement ( I put the condition to input == input). I then seperate the input into if, else if, and else statements to give the desired out put, and it works fine for the most part. The users first input, and subsequently the input that determines what output is given, is int. However while testing the program I accidentally hit a letter and inputted it, and it sent it into an infinite loop.

I figure that's because the letter is char and the input is supposed to be int. So is there anyway for the program to pick up on char characters and give an output such as "invalid" or something to prevent it from going off into an infinite loop.?
You will have to check cin.good(), and if it isn't good, then you should output your error msg then call cin.clear(); to clear the error, etc.
Yes, there is, sort of. You need to store the output in a char and then use strtol(). Normally its a Bad Idea to store userinput directly into an integer, because of this exact problem.
http://www.augustcouncil.com/~tgibson/tutorial/iotips.html
http://www.cplusplus.com/reference/clibrary/cstdlib/strtol.html

(Be awere that if the char is invalid, strtol() will store 0 into the integer. You have to check or this is the case, since its probably not what you want)
Last edited on
You could see if the next character in the stream (cin.peek()) is numeric (isdigit())
I'll try to decipher exactly how to do that in a moment, but real quick another stupid question. What would be the best way to go about aligning right? I read it's defaulted but I can't figure out what's aligning left then.
Anyone know how to align right?
You have to expect some delay for answers.

1
2
3
cout << setw( 10 )
     << left
     << "left";

left


1
2
3
cout << setw( 10 )
     << right
     << "right";

right


Hope this helps.
(Note: a lot of times, you can just write a little program to try it out and see what happens.)
Topic archived. No new replies allowed.