Search code examples
cwinapistrtol

How could I check whether strtol parsed anything at all?


strtol parses out a long integer from a given string. Okay. But how could I check whether there was parsed anything at all?

For example:

  • using strtol on the following string yields 0:
    0abcdef
  • however, using strtol on the following string yields 0 too:
    abcdef

So, I have no indicator whether the function parsed a valid 0 or did not parse anything at all and thus returns 0.

How do I verify whether strtol worked correct or returned with an error? Are there any alternatives?

I read that strtol sets an errno on Unix, but I'm especially interested in the Win32 platform.


Solution

  • That's the signature of strtol():

    long int strtol(const char *nptr, char **endptr, int base);
    

    If endptr is not NULL, strtol() stores the address of the first invalid character in *endptr. So you can simply compare *endptr to nptr afterwards and if it differs, strtol() has parsed the characters before *endptr.