c - How to parse char str and create a new array of ints -
i want fill array int values extracted buffer. want like:
char buffer[buff_max]; int numbers[num_max]; int = 0; fgets(buffer, buff_max, stdin); while(sscanf(buffer, "%d", &numbers[i]) == 1) { ++i; }
but having kinds of problems using method. perhaps has \n in buffer? seems same value assigned every element , if type in greater around 130, garbage value stored.
the user typing in like:
12 543 5 234 9
and want these values stored in numbers[]
5 different elements. there different amounts of numbers in buffer each time (depending on user types in).
you can find out sscanf()
got in parsing string using %n
conversion specifier, thus:
char buffer[buff_max]; int numbers[num_max]; int = 0; int offset = 0; int newlen; if (fgets(buffer, buff_max, stdin) != 0) { while (sscanf(buffer + offset, "%d%n", &numbers[i], &newlen) == 1 && < num_max) { ++i; offset += newlen; } }
testing
#include <stdio.h> enum { buff_max = 1024, num_max = 32 }; int main(void) { char buffer[buff_max]; int numbers[num_max]; int = 0; int offset = 0; int newlen; if (fgets(buffer, buff_max, stdin) != 0) { while (sscanf(buffer + offset, "%d%n", &numbers[i], &newlen) == 1 && < num_max) { printf("found: numbers[%d] = %d\n", i, numbers[i]); ++i; offset += newlen; } } return 0; }
input string:
123 456 789 0123456
output:
found: numbers[0] = 123 found: numbers[1] = 456 found: numbers[2] = 789 found: numbers[3] = 123456
the %n
modifier added in c89, not many people know there. 'works' in printf()
family of functions, more lethal there because people aren't used seeing output parameters in printf()
format string. @ least scanf()
et al, expecting inputs.
beware of 'format string vulnerabilities', decent search term use in favourite search engine. should beware of them, independently of question.
[updated check fgets()
not indicate error or eof. check read operations expected. well, — if you're recovering error , don't care read because won't using it, maybe don't need check. if you're going use read data, should check got data work with.]
Comments
Post a Comment