Domanda

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.

È stato utile?

Soluzione

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.

Altri suggerimenti

Use the second parameter of strtol : it's a char **. It will be filled with the first invalid char: take a look at this manpage.

Example:

#include <stdlib.h>
int main()
{
    char       *ptr = 0;
    const char *str = "1234abcd";

    printf("%d\n", strtol(str, &ptr, 10)); // -> 0
    printf("ptr: %c\n", *ptr); // -> 'a'
    while (*str && *str != *ptr)
    {
        printf("parsed: %c\n",  *str); // -> '1' '2' '3' & '4'
        ++str;
    }
    return 0;
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top