c - Given an array of characters, how can i take multiple digits from this array and assign it to an int value? -
so have char array such
char *array = "hello name steven 123*3";
and want extract 123
expression , put in int
.
i know can like
int firstnum = array[15] - '0';
(assuming 1 15th character in array), , give me firstnum = 1
.
but able whole 123
number single integer, , im not quite sure how this.
any appreciated
edit: found out called strtol, unsure of how use it.
i'm thinking long numberwanted = strtol(array[15], *p, 10); how let know when stop? or stop once non-int or non-long? , *p?
try using sscanf
.
int n1 = 0, n2 = 0; char ch = 0; char *array = "hello name steven 123*3"; sscanf(array, "%*[^0-9] %d %c %d", &n1, &ch, &n2);
this assumes prefix string never contain digit. if contain digit, read (which assumes data consists of: prefix string, 1 or more digits, 1 character, 1 or more digits.
int n1 = 0, n2 = 0; char ch = 0; char *array = "hello name steven 123*3"; size_t = strlen(array); while (--i >= 0 && isdigit(array[i])) ; sscanf(array+i+1, "%d", &n2); ch = array[i]; while (--i >= 0 && isdigit(array[i])) ; sscanf(array+i+1, "%d", &n1);
Comments
Post a Comment