int question

• 09-01-2008
erik90
int question
This is probably an easy one....

how do I determine if a number is a integer or not.

ex:

a number: 3
correct

a number: 3.25
its not an integer write a new number:.....etc
• 09-01-2008
matsp
Well, yes and no.

If you are reading integers, you will ALWAYS read an integer value if there is something that starts with digits entered. Once something non-digit turns up (such as newline, the letter 'a' or symbols etc like space, period, comma), this is left behind in the input buffer. So 3.25 will be read in as 3, then .25 is left behind in the input buffer.

So you would have to determine if there is something in the input buffer that is not what you expected.

Or we can read the "number" as a string, and then attempt to convert the string into a number somehow. Again, we need to determine if the whole input was consumed or just some of it.

Note also that input such as 19999999999999 is too large to fit in an integer, so it is technically incorrect input in a C program, whilst mathematically it is of course still an integer.

--
Mats
• 09-01-2008
Elysia
My favorite way is to read into a string and use boost::lexical_cast to cast to the target type.
The function throws boost::bad_lexical_cast is the source can't be converted into the target type.
But this assumes you have a little knowledge about exceptions in C++.