determining if an integer is a legal integer

This is a discussion on determining if an integer is a legal integer within the C++ Programming forums, part of the General Programming Boards category; I have a very simple question that I have not been able to find the answer to anywhere. How do ...

  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
    Super Moderator
    Join Date
    Sep 2001
    Posts
    4,913
    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,325
    Your question is vague, but there was just a thread about this:

    Library Function to verify Int

    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-20-2009, 11:37 PM
  2. Link List math
    By t014y in forum C Programming
    Replies: 17
    Last Post: 02-20-2009, 05: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, 09:43 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21