Skip to main content
gamedev.net
🔒 Locked

Bad Input (C++)

Started by Ed C 4 replies 1k views
Original Post
Ed C
Ed C
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.
DerekSaw
DerekSaw
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 n the event horizon" o
Ed C
Ed C
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
Zipster
Zipster
After the read...


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


You get the picture
Sneftel
Sneftel
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.
Kingstone426
Kingstone426
#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]
}

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.