string validation for int and long (strisint, strislong)

From: jake1138 (cooljake_at_gmail.com)
Date: 02/25/05


Date: 24 Feb 2005 15:53:10 -0800

Maybe this is a newbie thing and everyone already knows how to do this,
but I figured I'd post these functions anyway in case someone finds
them useful. I used Jack Klein's example (see link below) and made
functions out of it.

http://home.att.net/~jackklein/c/code/strtol.html

Here are functions that will validate a string to see if it represents
an integer or long, respectively:

/*
 * checks to see if string is an integer
 *
 * returns 1 if true, 0 if false
 */
int strisint(const char *str, size_t size)
{
    char *endptr;
    long longint;

    errno = 0;
    longint = strtol(str, &endptr, 10);
    if (errno == ERANGE || longint < INT_MIN || longint > INT_MAX
        || endptr == str || *endptr != '\0') {
        return 0;
    } else {
        return 1;
    }
}

/*
 * checks to see if string is a long integer
 *
 * returns 1 if true, 0 if false
 */
int strislong(const char *str, size_t size)
{
    char *endptr;
    long longint;

    errno = 0;
    longint = strtol(str, &endptr, 10);
    if (errno == ERANGE || endptr == str || *endptr != '\0') {
        return 0;
    } else {
        return 1;
    }
}



Relevant Pages

  • Re: help getting substring
    ... I need a program to extract a substring from the following pattern ... char* deangle ... What does deangle do when passed a string of the form ... char *deangle(char *str) ...
    (comp.lang.c)
  • Re: How to Return an array of strings in C (char**)
    ... If your code in the calling function really uses a char* that points ... to a literal string, change it to use an array. ... any user defined function or object name beginning with str. ... ptr is a char**. ...
    (comp.lang.c)
  • Text to string program
    ... This is a program to convert a text file to a C string. ... char *fnametoid; ... char *str; ... ch - an escaped character ...
    (comp.lang.c)
  • callllib dll
    ... char* stringToUpper{ ... MATLAB character array, str, and pass it as the input ... THIS WAS A MIXED CASE STRING ... contain the address of the MATLAB character array, ...
    (comp.soft-sys.matlab)
  • Re: Converting string to char*
    ... > char array. ... What's a C++ string? ... > int convertStringToChar(string& str, char* data) ...
    (comp.lang.c)