My string input can either be "-c123" or "-c 123".
What's the best way to scan the string to get the number out?
Printable View
My string input can either be "-c123" or "-c 123".
What's the best way to scan the string to get the number out?
If you don't need tight control, try atoi().
If you want tighter control of errors, prefer strtol().
Read the function descriptions!!!
You can also use sscanf() withy a littel more control than atoi() and a little less than strtol() ...Code:char input1[] = "-c123";
char input2[] = "-c 123";
int val1atoi = atoi(input1 + 2);
int val2atoi = atoi(input2 + 2);
char *err;
errno = 0; int val1strtol = strtol(input1 + 2, &err, 10); /* test *err, val1strtol, and errno */
errno = 0; int val2strtol = strtol(input2 + 2, &err, 10); /* test *err, val2strtol, and errno */
All 3 funtions above properly ignore whitespace.Code:char input[] = "-c 123";
int val;
if (sscanf(input, "-c%d", &val) != 1) /* error */;
thanks a ton. I was messing around with sscanf() but didn't really wrap my head around it.