home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1993 #3 / NN_1993_3.iso / spool / comp / lang / c / 20313 < prev    next >
Encoding:
Text File  |  1993-01-28  |  2.0 KB  |  55 lines

  1. Newsgroups: comp.lang.c
  2. Path: sparky!uunet!friend!friend!rich
  3. From: rich@kastle.com (Richard Krehbiel)
  4. Subject: Re: strtol() return values
  5. In-Reply-To: md@sco.COM's message of Tue, 26 Jan 1993 12:36:14 GMT
  6. Message-ID: <RICH.93Jan28094746@rich.kastle.com>
  7. Lines: 42
  8. Sender: news@friend@kastle.com (News)
  9. Organization: Kastle Development Associates, Arlington, VA, USA
  10. References: <ric.728002623@updike> <1993Jan26.123614.10840@sco.com>
  11. Date: Thu, 28 Jan 1993 09:47:46 GMT
  12.  
  13. In article <1993Jan26.123614.10840@sco.com> md@sco.COM (Michael Davidson) writes:
  14.  
  15. >   ric@updike..sri.com (Richard Steinberger) writes:
  16. >
  17. >   >    strtol() returns a long int when successful.  If a non-numeric
  18. >   >string is encountered, 0 is returned.  Unfortunately, errno doesn't seem
  19. >   >to be set.  Here's the question:  If a string like, "0" or "000"
  20. >   >is encountered, I also get a 0 returned from strtol(). Is there an easy,
  21. >   >elegant way to check for this without examing each char?  
  22. >
  23. >   Yes - try something like this:
  24. >
  25. >       char    **p;
  26. >
  27. >       if ((value = strtol(str, p, 0)) == 0 && *p == str)
  28. >           printf("strtol() failed!!\n");
  29. >
  30.  
  31.     char    *p;
  32.     if ((value = strtol(str, &p, 0)) == 0 && p == str)
  33.         printf("strtol() failed!!\n");
  34.  
  35.     Note the change from char **p to *p.  The previous fragment left
  36. out (possibly as an exercise to the reader) the technicality of "where
  37. does p point?"
  38.  
  39.     Since failure is easily detected by the pointer compare, you can
  40. leave out the compare value==0:
  41.  
  42.     value = strtol(str, &p, 0);
  43.     if (p == str)
  44.         printf("strtol() failed!!\n");
  45.  
  46.     Unrelated question:
  47.  
  48.     I had to write a strtoul function because my environment didn't
  49. provide one.  I couldn't find anything which says what strtoul should
  50. do if the base parameter is not 0 or 2 through 36.  What should it do?
  51. Is this implementation-defined?  (Mine just uses base ten.)
  52. --
  53. Richard Krehbiel              rich@kastle.com or richk@grebyn.com
  54. OS/2 2.0 will do for me until AmigaDOS for the 386 comes along...
  55.