# int question

This is a discussion on int question within the C++ Programming forums, part of the General Programming Boards category; This is probably an easy one.... how do I determine if a number is a integer or not. ex: a ...

1. ## 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

2. 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

3. 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++.