Click to See Complete Forum and Search --> : C++ question. No i dont want you to do my homework.


Bazoukas90
06-27-2001, 08:59 PM
i wrote a program and I would like to have it so that it will give a warning message if you enter a letter i nstead of numbers. I am not using switch statements to put "default;". Its written with "for" and "if else " statements. Anyone can give me an idea about this one to do it with out overflowing each statement with "while" commands?

maha_x
06-28-2001, 09:12 AM
I dont know what you are doing, but the "numbers" in the keycodes are lined up meaning you can use a simple test:

if(input >= '1' && input <= '0')

In this case you'd have the 'if' execute when the typed letter was 1, 2, 3 ... 0.

Then again, you could be reading more than one char. Do you read it to string? Do you convert it to numeric? In this case the conversion should return with a error (if letters present).

Or you could be coding for Win32, which would make things more difficult (regarding reading input etc.)...


------------------
__
Yep, I'm one of them

stoo
06-28-2001, 09:28 AM
Isn't there an "isInteger" function somewhere (operates on strings, returns true if the string is a representation of an int, false otherwise)? I remember writing one myself and kicking myself when I found the function... http://www.sharkyforums.com/ubb/frown.gif

------------------
Stoo

gammaray51
06-28-2001, 10:30 AM
you could also typecast the input from a char to an int, then check to see if it is part of the numberic ACSII table.

Strogian
06-28-2001, 11:05 AM
The function is called isdigit() (#include <ctype.h> )

Zoma
06-28-2001, 01:36 PM
I'd probably read in input as a string of length 256.

Then I'd loop through each character and compare it to the ascii values that represent numbers. If the type I was supposed to be reading in was signed, I'd also allow for the first character to be a '-' or a '+'. I'd send a "NAN" error if one character was wrong.

Then check to see if strlen was greater than the size of the data (eg, 5 characters for an unsigned short). If the size is greater, I'd return an overflow. If it's smaller, the string is fine.

Otherwise, it's the same length and another test must be done. I'd then check the MSB against the largest MSB of the type (eg, 6 is the largest value the MSB an unsigned short can have). I'd have to loop through each character, since 64000 is ok, but 66000 is not.

If it passes all of this, I accept the string. A conversion loop is pretty easy to write. The entered value would then be stored in the correct numerical type (eg, unsigned short).