could anyone tell me a way to test if cin is a type double or int?
thx
Printable View
could anyone tell me a way to test if cin is a type double or int?
thx
cin requires user input. I'd store user input in a string and parse the string to determine if input were valid int, valid double, or invalid as either int or double. I'd call atoi() to convert to int or atof() to convert to double.
^
in simple C++ language u mean? (ur talking to to first year engineer programmer)
It means the only type that will always have valid input from the keyboard is a string. So accept the input into a string. Then evaluate the string to see if any of the char are invalid for the type you want. For example, if there is a decimal, it can't be an int. If there is any letter other than e it can't be numeric input. If there is any non-alphabetical, non-digit char other than +, -, (, or ), then it can't be numerical. Alternatively, if all char are digits, then it can only be an int or invalid (if there are 18 digits, it won't fit in an int so its invalid). If all the char are digits except one decimal point, then it is a double. Allowing input in scientific notation is a bit trickier to validate, but not impossible. Once you have determined what type it is--int, double, invalid, then you can use the standard atoi() to convert the string to type int or atof() to convert the string to type double. Since all ints are also doubles, you will need to decide whether doubles that could be ints are ints or doubles.
I suppose you could take advantage of the last relationship and attempt to put input into type double. If it's a valid type double then you can see if the decimal portion (mantissa?) is zero. If so, then you could arbitrarily say the number is an int, not a double.
what about the "0x" prefix for hexadecimal?Quote:
Originally Posted by elad
To me int and double are base 10 only. If you think that 0x is valid, I won't argue one way or the other, then you can set up the validation code to allow for that input syntax as well.