Bad Input (C++)

Started by
4 comments, last by Ed C 21 years, 3 months ago
In my program the user has to input a char, and then my program processes it. If they input a string in said my program goes wrong. How can i stop this. PS I am using std::cin to get the char from the user.
Advertisement
You can cin a string, and then check if the length is more than one. Otherwise proceed as planned.

...err... I'm still not sure what you mean. (Did I got it correct?) Pls clarify more.

[edited by - DerekSaw on January 24, 2003 4:41:33 AM]
"after many years of singularity, i'm still searching on the event horizon"
That''s the right idea, but i''m sure there''s a better way than having cin a string. It seems like a waste of memory if there is a better way
After the read...

if(!std::cin){   // User is a moron}else{   // User isn''t quite a moron} 


You get the picture
Just to expand on what Zipster was saying, the user being a moron puts the stream into a "fail" state which needs to be cleared before input can continue. check out the iostream documentation for more details. Zipster''s code invokes the implicit void* conversion operator on cin, which returns NULL if the stream is in a fail state.

Don''t listen to me. I''ve had too much coffee.
#include "conio.h"

void main() //Or whatever your functions called
{
int myInput = getch();//Reads one character from the keyboard
//Now myInput holds the ASCII code for that character
if (myInput==13) //ASCII-value 13 which means [ENTER]
//[do_something]
}

This topic is closed to new replies.

Advertisement