Thread: int question

  1. #1
    Registered User
    Join Date
    Sep 2008
    Posts
    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. #2
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    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
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  3. #3
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    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++.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 48
    Last Post: 09-26-2008, 03:45 AM
  2. Replies: 8
    Last Post: 03-10-2008, 11:57 AM
  3. getting a headache
    By sreetvert83 in forum C++ Programming
    Replies: 41
    Last Post: 09-30-2005, 05:20 AM
  4. Half-life SDK, where are the constants?
    By bennyandthejets in forum Game Programming
    Replies: 29
    Last Post: 08-25-2003, 11:58 AM
  5. How do you search & sort an array?
    By sketchit in forum C Programming
    Replies: 30
    Last Post: 11-03-2001, 05:26 PM