I am trying to use C to parse a file containing several lines of integers, separated by spaces, into a dynamic array of dynamic int arrays. Each row will be an array in an array of arrays. The number of rows and elements in each row is inconsistent.
What I have done so far is to use fgets to capture each line as a string.
I cannot, however, figure out how to parse a string of integers, separated by spaces.
I thought I could use sscanf (because fscanf can be used to parse a whole file of integers, separated by spaces). However, sscanf seems to have different functionality. sscanf only ever parses the first number in a string. I assume that since a string is a string, it is not a stream.
I was looking for a way to make a stream from a string, but this does not look like it is available in C (I cannot use non-standard libraries).
char* line;
char lineBuffer[BUFFER_SIZE];
FILE *filePtr;
int value;
...
while((line = fgets(lineBuffer, BUFFER_SIZE, filePtr)) != NULL) {
printf("%s\n", lineBuffer);
while(sscanf(lineBuffer, "%d ", &value) > 0) {
printf("%d\n", value);
}
}
Is there something I can use to parse a string. If not, is there an alternative to this whole system? I would prefer not to use REGEX.
source
share