C++ istream input handling
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
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.
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.
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 ]
You could loop through your string, subtracting ''0'' from each char and testing to see if it falls in the 0-9 range.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement