strtol() and zero

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Marlene Stebbins

    #1

    strtol() and zero

    Suppose I'm using strtol() to convert a command line string
    to a number and I want to check that the input to strtol() is
    not non-numeric. strtol() returns zero if input is non-numeric,
    so I can write something like this:

    if((x = strtol(argv[1], NULL, 10))==0)
    exit(EXIT_FAILU RE);

    That catches non-numeric input alright, but zero is a perfectly
    good number that might be input to my program. How can I use
    strtol() to convert zero while checking for non-numeric input?
  • Joe Wright

    #2
    Re: strtol() and zero

    Marlene Stebbins wrote:[color=blue]
    > Suppose I'm using strtol() to convert a command line string
    > to a number and I want to check that the input to strtol() is
    > not non-numeric. strtol() returns zero if input is non-numeric,
    > so I can write something like this:
    >
    > if((x = strtol(argv[1], NULL, 10))==0)
    > exit(EXIT_FAILU RE);
    >
    > That catches non-numeric input alright, but zero is a perfectly
    > good number that might be input to my program. How can I use
    > strtol() to convert zero while checking for non-numeric input?[/color]

    Assume this prototype..

    long strtol(const char *s, char **endp, int base);

    Rather than passing NULL as the second argument, pass the address of
    a local char* like this..

    long x;
    char *end;
    x = strtol(argv[1], &end, 10);
    if (argv[1] == end) exit(EXIT_FAILU RE);

    --
    Joe Wright mailto:joewwrig ht@comcast.net
    "Everything should be made as simple as possible, but not simpler."
    --- Albert Einstein ---

    Comment

    • Jack Klein

      #3
      Re: strtol() and zero

      On Tue, 14 Dec 2004 21:47:31 GMT, Marlene Stebbins <marlene@mail.c om>
      wrote in comp.lang.c:
      [color=blue]
      > Suppose I'm using strtol() to convert a command line string
      > to a number and I want to check that the input to strtol() is
      > not non-numeric. strtol() returns zero if input is non-numeric,
      > so I can write something like this:
      >
      > if((x = strtol(argv[1], NULL, 10))==0)
      > exit(EXIT_FAILU RE);
      >
      > That catches non-numeric input alright, but zero is a perfectly
      > good number that might be input to my program. How can I use
      > strtol() to convert zero while checking for non-numeric input?[/color]

      Explanation and illustration:



      --
      Jack Klein
      Home: http://JK-Technology.Com
      FAQs for
      comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
      comp.lang.c++ http://www.parashift.com/c++-faq-lite/
      alt.comp.lang.l earn.c-c++

      Comment

      Working...