简体   繁体   中英

Scanning a list of strings in C

it's been a long since I've coded in C, and it seems like I forgot how to do basic things.

I need to achieve the following:

In the scanf, the users will enter various words divided by the char ' ' , for example:

"check hello world"

I want to keep the first word into a string, and all the rest into an array of strings. In this case, the result would be:

char first[] = "check";
char *args[] = {"hello", "world"};

The only constraint I know is that the OVERALL size is less or equal to 100 chars. (including first+args).

Any advice on how to achieve this?

I think your question seems to be a simple use case for strtok as pointed out in comments. You can declare a string for input and an array for args like this:

    char input[100];
    char first[100];
    char args[100][100];
    const char delimiter[2] = " ";

Then you would take string as input. I used fgets to take input:

    fgets(input, 100, stdin);
    input[strcspn(input, "\n")] = 0; // Trim trailing newline added by fgets

Once you got your input, you can easily use strtok to get first and other argument strings like this:

    // Get First
    char *token = strtok(input, delimiter);
    // Copy token to first
    strcpy(first, token);

    // Get Args
    while (token != NULL) {
        token = strtok(NULL, delimiter);
        if (token != NULL) {
            // copy token to args[] array
            strcpy(args[nArgs], token);
            nArgs++;
        }
    }

I tested it with this code and it seems to be working okay:

c-posts : $ gcc strtokscanstring.c 
c-posts : $ ./a.out 
check hello world
first: check
nArgs: 2
arg[0] = hello
arg[1] = world

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM