Thread: How can I determine whether a string represents an integer or not?

  1. #1
    1.b4 e5 2.a3 d5 3.d4 exd
    Join Date
    Jan 2003
    Posts
    167

    How can I determine whether a string represents an integer or not?

    How can I determine whether a string represents an integer or not?
    AIM: MarderIII

  2. #2
    Well, you could use atoi (Ascii TO Integer) or the like (atof, atol, etc) and determine if the result is a number. atoi returns 0 if the string was not a number. Possibly your string IS the number 0, so just for added safety, in this example we check to make sure that both the value is non-zero and the string does not contain zero.

    Code:
    int num;
    char * string = "12345";
    
    num = atoi( string );
    
    if (num == 0 && string[0] != '0')
       printf("Not a Number!");
    else
       print("Number is: %i", num);
    "There's always another way"
    -lightatdawn (lightatdawn.cprogramming.com)

  3. #3
    ... Come to think of it, alternatly you could parse your string for valid integers, either ignoring invalid characters (alphabet, etc) or by simply flagging the string as non-numeric if one is found. i.e.

    Code:
    BOOL IsValidNumber(char * string)
    {
       for(int i = 0; i < strlen( string ); i ++)
       {
          //ASCII value of 0 = 48, 9 = 57. So if value is outside of numeric range then fail
          //Checking for negative sign "-" could be added: ASCII value 45.
          if (string[i] < 48 || string[i] > 57)
             return FALSE;
       }
    
       return TRUE;
    }
    "There's always another way"
    -lightatdawn (lightatdawn.cprogramming.com)

  4. #4
    Registered User Cela's Avatar
    Join Date
    Jan 2003
    Posts
    362
    Or to be more thorough you could check that all of the string is valid in every conceivable way :-)
    Code:
    #include <iostream>
    #include <cstdlib>
    #include <string>
    #include <limits>
    #include <cerrno>
    
    using namespace std;
    
    bool is_number(string& src)
    {
      const char *start = src.c_str();
    
      errno = 0;
      char *end;
      long string_value = strtol(start, &end, 10);
    
      if (
         errno == ERANGE ||                                 // Did we set off errno?
         string_value > numeric_limits<int>::max() ||       // Is it too big?
         string_value < numeric_limits<int>::min() ||       // Too small?
         static_cast<unsigned>(end - start) != src.length() // Non-numerics?
         )
      {
        return false;
      }
    
      return true;
    }
    
    int main()
    {
      string s = "12345";
    
      if (is_number(s))
      {
        cout<<"It's a number!"<<endl;
      }
    }
    *Cela*

  5. #5
    1.b4 e5 2.a3 d5 3.d4 exd
    Join Date
    Jan 2003
    Posts
    167
    Im teaching myself c++ and this board is a LOT of help. I looked at the code offered and managed to get the below to work for Borland C++ 5.02. I think this is what I want.

    Code:
    #include <iostream>
    #include <string>
    #include <limits>
    
    int main()
    {
    int num;
    char string[256];
    cin.getline(string, 256, '\n');
    num = atoi( string );
    
    if (num == 0 && string[0] != '0')
    {
    cout <<"Not a Number!";
    }
    else
    {
    cout<<"Number is: "<<num;
    }
    return 0;
    }
    AIM: MarderIII

  6. #6
    Registered User Cela's Avatar
    Join Date
    Jan 2003
    Posts
    362
    >>I think this is what I want.
    Close enough, if you're teaching yourself C++ then rock solid validation might be more than you want :-)
    *Cela*

  7. #7
    1.b4 e5 2.a3 d5 3.d4 exd
    Join Date
    Jan 2003
    Posts
    167
    Rock-solid validation is what drives me to learn more!
    AIM: MarderIII

  8. #8
    Celas example is accurate, inclusive, and safe... though a little excessive.

    >>Rock-solid validation is what drives me to learn more!

    Bravo. Its always nice to see people who want to learn. I'll offer some related information.

    Something to look for when processing something like this, is that your char * string is valid. The line "... && string[0] != '0'" will explode if string is not a valid pointer. So checks like:

    if (string != NULL) ... //proceed with code

    could prove useful. In your particular case that would be useless as string is not a pointer, but something like that would be a smart idea using the IsValidNumber(...) function example.
    "There's always another way"
    -lightatdawn (lightatdawn.cprogramming.com)

  9. #9
    Or u can use the standard lib functions -

    #include <locale>

    isdigit(); //This fxn determines whether a letter in a string is a numerical value '3' is numerical 'L' is not

    I think this used to be in the <cctype.h> header as I remember reading that those checking functions were there but MSDN says it's in the <locale> header. Go figure?
    My Avatar says: "Stay in School"

    Rocco is the Boy!
    "SHUT YOUR LIPS..."

  10. #10
    Registered User Cela's Avatar
    Join Date
    Jan 2003
    Posts
    362
    >>Celas example is accurate, inclusive, and safe... though a little excessive.
    There's nothing wrong with being excessive in the right situations, like nuclear reactor or space station controllers :-) But you're right, it's a little much for most normal use
    *Cela*

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. String Class
    By BKurosawa in forum C++ Programming
    Replies: 117
    Last Post: 08-09-2007, 01:02 AM
  2. String issues
    By The_professor in forum C++ Programming
    Replies: 7
    Last Post: 06-12-2007, 09:11 AM
  3. Custom String class gives problem with another prog.
    By I BLcK I in forum C++ Programming
    Replies: 1
    Last Post: 12-18-2006, 03:40 AM
  4. Another overloading "<<" problem
    By alphaoide in forum C++ Programming
    Replies: 18
    Last Post: 09-30-2003, 10:32 AM
  5. lvp string...
    By Magma in forum C++ Programming
    Replies: 4
    Last Post: 02-27-2003, 12:03 AM