the prototype as you may know is
long int strtol(const char *str, char **endptr, int base)
where str
is the original string and endptr
is the address of a pointer to the rest of the string after a number is found. base
is, well, the base.
strtol()
returns 0 when it finds no number. Sure it returns 0 when it finds a 0 and then you must check the remaining data and eventually start over again.
This
Original string: "2001 2002 2003 2004 0 2005"
2001 parsed string now: " 2002 2003 2004 0 2005"
2002 parsed string now: " 2003 2004 0 2005"
2003 parsed string now: " 2004 0 2005"
2004 parsed string now: " 0 2005"
0 was parsed: may be just the end of input
5 bytes remaining at the string: " 2005"
is the output of the short program below and may help you understand the mechanic
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char* argv[])
{
const char* pattern =
"2001 2002 2003 2004 0 2005";
char* input = (char*)pattern;
char* after = NULL;
long long int num1 = strtol(input, &after, 10);
printf("Original string: \"%s\"\n\n", pattern);
do
{
printf("%8lld parsed\tstring now: \"%s\"\n", num1, after);
input = after;
num1 = strtol(input, &after, 10);
} while (num1 != 0);
printf("\n0 was parsed: may be just the end of input\n");
printf("\n%ud bytes remaining at the string: \"%s\"\n",
strlen(after), after);
return 0;
};
// Compiled under MSVC 19.27