Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C, parsing a string of multiple whitespace separated integers

I am attempting to use C to parse a file containing multiple rows of whitespace separated integers into a dynamic array of dynamic int arrays. Each row will be an array in the array of arrays. The number of rows, and elements in each row are non-constant.

What I have done so far is to use fgets to grab each line as a string.

I cannot, however, figure out how to parse a string of whitespace separated integers.

I thought I could use sscanf (because fscanf can be used to parse a whole file of whitespace separated integers). However, it appears that sscanf has different functionality. sscanf only ever parses the first number in the string. My guess is that, because the line is a string is not a stream.

I've looked around for a way to make a stream out of a string, but it doesn't look like that is available in C (I am unable to use nonstandard 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 that I can use to parse a string. If not, is there an alternative to this whole system? I would prefer not to use REGEX.

like image 919
Don Subert Avatar asked Jan 30 '15 10:01

Don Subert


1 Answers

Use strtol() which gives a pointer to the end of the match if there is one, and a char pointer to store the current position:

    while((line = fgets(lineBuffer, BUFFER_SIZE, filePtr)) != NULL) {

    printf("%s\n", lineBuffer);
    char* p = lineBuffer;
    while(p < lineBuffer+BUFFER_SIZE ) {
        char* end;
        long int value = strtol( p , &end , 10 );
        if( value == 0L && end == p )  //docs also suggest checking errno value
            break;

        printf("%ld\n", value);
        p = end ;
    }
}
like image 159
reader Avatar answered Nov 12 '22 19:11

reader