C - Filling array from specific single line input

2019-08-24 19:39发布

I am a novice and for my school programming exercise I need to make integer array from specified input. Input look like this:

1000: { 250, 500, 750 } (enter)

My very basic code is capable to scan only numbers separated with whitespace.

#include <stdio.h>
#include <stdlib.h>
#define LEN 10
long int array[LEN];

    int main()
    {   
        long int i;

        for (i =0; i < LEN; i++)
            {
            scanf("%li", &array[i]);
            }

    return 0;
    }

I have a static array and I need to fill it with numbers in {} brackets. The number before ":" symbol (1000 in this case) I could scan as a single variable or as a 0th element of array. Sould I use some modified scanf? But I think the way here is some while cycle with scanf. Sometimes is array bigger than amout of given numbers so I need to end cycle with "}" symbol. Thanks for ideas.

1条回答
太酷不给撩
2楼-- · 2019-08-24 20:31

Consider using fgets to read a line. Parse the line with sscanf. The %n specifier will report the number of characters processed by the scan. Accumulating those values will allow for iterating through the line.

#include <stdio.h>
#include <stdlib.h>

#define SIZE 4000
#define LIMIT 500

int main( void) {
    char line[SIZE] = "";
    char bracket = 0;
    long int value[LIMIT] = { 0};
    int result = 0;
    int input = 0;
    int offset = 0;
    int span = 0;

    printf ( "enter values x:{w,y,...,z}\n");
    if ( fgets ( line, sizeof line, stdin)) {
        //scan for long int, optional whitespace, a colon,
        //optional whitespace, a left brace and a long int
        if ( 2 == ( result = sscanf ( line, "%ld : {%ld%n", &value[0], &value[1], &offset))) {
            input = 1;
            do {
                input++;
                if ( LIMIT <= input) {
                    break;
                }
                //scan for optional whitespace, a comma and a long int
                //the scan will fail when it gets to the right brace }
                result = sscanf ( line + offset, " ,%ld%n", &value[input], &span);
                offset += span;//accumulate processed characters
            } while ( 1 == result);
            //scan for optional space and character ie closing }
            sscanf ( line + offset, " %c", &bracket);
            if ( '}' != bracket) {
                input = 0;
                printf ( "line was not terminated with }\n");
            }
        }
    }
    else {
        fprintf ( stderr, "fgets EOF\n");
        return 0;
    }

    for ( int each = 0; each < input; ++each) {
        printf ( "value[%d] %ld\n", each, value[each]);
    }

    return 0;
}
查看更多
登录 后发表回答