Thread: determining if an integer is a legal integer

  1. #1
    Registered User
    Join Date
    Oct 2005
    Posts
    1

    determining if an integer is a legal integer

    I have a very simple question that I have not been able to find the answer to anywhere. How do you determine if an integer is a legal integer value? Thanks.

  2. #2
    Registered User
    Join Date
    Sep 2001
    Posts
    4,912
    Well it depends on what exactly you're doing. If you try to assign the string "Hello World!" to an int, you'll get a compiler error. If you read in a character, and want to know if an integer was entered, you could check the data using the isdigit() funcion in <cctype>.

  3. #3
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    Your question is vague, but there was just a thread about this:

    http://cboard.cprogramming.com/showthread.php?t=70234

    Here is the final version of my code that works on a string input and handles negative numbers, overflow, octal and hex input, etc.
    Code:
    #include <sstream>
    #include <string>
    
    bool is_int(const std::string& s)
    {
        int i;
        std::istringstream istr(s);
        istr.unsetf(std::ios::dec);
        if (!(istr >> i))
            return false;
    
        return istr.rdbuf()->in_avail() == 0;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. memory issue
    By t014y in forum C Programming
    Replies: 2
    Last Post: 02-21-2009, 12:37 AM
  2. Link List math
    By t014y in forum C Programming
    Replies: 17
    Last Post: 02-20-2009, 06:55 PM
  3. Looking for constructive criticism
    By wd_kendrick in forum C Programming
    Replies: 16
    Last Post: 05-28-2008, 09:42 AM
  4. No Match For Operator+ ???????
    By Paul22000 in forum C++ Programming
    Replies: 24
    Last Post: 05-14-2008, 10:53 AM
  5. load gif into program
    By willc0de4food in forum Windows Programming
    Replies: 14
    Last Post: 01-11-2006, 10:43 AM