If the first part of the string is always a number, look at the strtoul function. On the man page:
strtoul - convert string to unsigned integer
LIBRARY
C Standard Library (libc, -lc)
SYNTAX
#include <stdlib.h> unsigned long strtoul(const char *restrict str, char **restrict endptr, int base);
DESCRIPTION
The strtoul () function converts a string to str into an unsigned long value. The conversion is performed in accordance with this base, which must be from 2 to 36 inclusive or be a special value of 0.
A line can begin with an arbitrary number of spaces (as defined by isspace(3) ), followed by one optional + or - sign. If base is zero or 16, the string may include the 0x prefix, and the number will be read in base 16; otherwise, the zero base is taken as 10 (decimal), unless the next character is 0 , in which case it is taken as 8 (octal).
The rest of the string is converted to an unsigned long value in an obvious way, stopping at the end of the string or on the first character, which does not give a valid digit in this database. (In the bases above 10, the letter A in upper or lower case represents 10, B represents 11, etc., with Z representing 35.)
If endptr not NULL , strtoul() stores the address of the first invalid character in *endptr . However, if there were no digits, strtoul() saves the original str value in *endptr . (Thus, if *str not \0 but **endptr is \0 by return, the entire string is valid.)
RETURN VALUES
The strtoul () function returns either the conversion result, or, if there was a major minus sign, the negation of the conversion result, if only the original (non-denied) value is overflowed; in the latter case strtoul() returns ULONG_MAX . In all cases, errno set to ERANGE . If the conversion cannot be performed, 0 is returned and the global variable errno is set to EINVAL .
The key here is the endptr parameter. It sets a pointer to where you need to continue parsing. If endptr == str , then you know that the string did not start with a number.
I like the strto___ family of functions much more than the ato__ functions, because you can set base (including the context-sensitive "base 0"), and since endptr tells me where to continue. (And for embedded applications, strto___ much smaller than __scanf functions.)
EDIT: Sorry to miss your comment. To use endptr , write code like this:
char* restOfLine = NULL; unsigned long result = strtoul(lineBuffer, 10, &restOfLine); if(restOfLine == NULL || restOfLine == lineBuffer) { } else {
Usually, the "handle error" clause returns or breaks or throws an exception or does something else to free itself from further processing, so you do not need an explicit else clause.