Jump to content
  • Advertisement

Archived

This topic is now archived and is closed to further replies.

Omnipotent

C++ istream input handling

This topic is 5800 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hey ALL, I just was wondering how to handle a case when I take in an input: int num; cin >> num; How do I handle it if the user enters in a character instead of a number?? Thanks in advance for the help

Share this post


Link to post
Share on other sites
Advertisement
well since technically all characters are "numbers" in the sense that each character is stored as an ASCII code, you have to figure it out

actually there''s a function called ATOI() which will convert a string to an int (hence Ascii TO Int=ATOI). it''s in stdlib.h.

if you want to use ATOI tho you''d have to change it to something like this:

char* numstring[20];
cin >> numstring;
int num=atoi(numstring);

and then num would be a number. in fact it even gets things like the negative sign

if the user enters text, i think atoi returns a zero. at least you don''t mess up your program with weird values of text

also if you want, there''s a function atof(), which does the same thing but it''s ascii to float.

umm thinking about it you could write your own input routine but that''d be hard... it''d involve getc() and putc() and other nastiness.. i dont'' do much console stuff, sorry : i''m a DX user personally.

Share this post


Link to post
Share on other sites

int num;
cin >> num;
if( cin.fail() ) // Input failed - that wasn''t an int
{
cin.clear(); // clear the flags (may not be necessary)
cin.ignore(); // get rid of the offending character

// We''re now ready to try again
}


cin.fail() will be true when the input failed.
cin.eof() will be true when the end of file is reached.
cin.bad() will be true if some major error occurs

cin.good() (or just ''cin'' in a bool context) will be true otherwise.

cin.clear() clears those flags.



Documents [ GDNet | MSDN | STL | OpenGL | Formats | RTFM | Asking Smart Questions ]
C++ Stuff [ MinGW | Loki | SDL | Boost. | STLport | FLTK | ACCU Recommended Books ]

Share this post


Link to post
Share on other sites
You could loop through your string, subtracting ''0'' from each char and testing to see if it falls in the 0-9 range.

Share this post


Link to post
Share on other sites

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!