Thread: check command line argument for numeric value

  1. #1
    Registered User
    Join Date
    Nov 2003
    Posts
    2

    check command line argument for numeric value

    Is there any C library function to check to see if the command line argument is a numerical value or string?

    char *ms = av[i];

    //how can i check to see if ms is a numerical value?
    if ( ms == NULL ) exit(1);

    Thanks

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Command line arguments are always strings.

    To check whether it is numeric or not, I'd suggest you use the strtol() function, and check its various return results.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Feb 2004
    Posts
    72
    Be careful though. I think that that returns 0 if the string is not numeric, i.e. you couldn't tell if you had 0 or garbage.

    Maybe check isdigit for each character if you're looking for an integer.

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    You're thinking of the rather dumb atoi(), which returns 0 on error

    strtol() returns a status value in errno, and the end pointer points to the first char after the string.

    Both of these taken together should be enough to classify any string as numeric or not.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  5. #5
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Pointer to List Iterator As Function Argument
    By bengreenwood in forum C++ Programming
    Replies: 8
    Last Post: 06-17-2009, 05:30 AM
  2. how to check input is decimal or not?
    By kalamram in forum C Programming
    Replies: 3
    Last Post: 08-31-2007, 07:07 PM
  3. Please check this loop
    By Daesom in forum C++ Programming
    Replies: 13
    Last Post: 11-02-2006, 01:52 AM
  4. Newbie Again
    By christianne in forum C Programming
    Replies: 14
    Last Post: 04-06-2006, 12:39 AM
  5. Thank you so much...
    By ta1samail in forum C++ Programming
    Replies: 0
    Last Post: 10-10-2001, 08:49 PM