How to set up a C function that splits user input

2019-07-17 05:35发布

问题:

I'm trying to develop a C function that takes a line of user input, say example this line:

1X 1X 3Y 1Z 1Z 1Z 1Z 2X 2X

(EDIT: This is just an arbitrary example of what the user will enter. In the actual program, they can enter anywhere between 1 and 48 digit-character pairs.)

The idea is that the user will insert this entire line, and it will split it up into 9 parts (each number and character pair is one part). Then, the number and the character pair will also be split from each other (I'm thinking for this part, they will both belong to a struct containing a numValue and charValue).

What can I use to split up the user's input? I'm relatively new to C.

回答1:

A function you could use to split the input string from the user is strtok() from the #include <string.h> library. Here is an example you can you use to split the input into nine parts.

#include <stdio.h>
#include <string.h>

main (){
    char word[] ="1X 1X 3Y 1Z 1Z 1Z 1Z 2X 2X";
    int i = 0;
    char *p = strtok(word, " ");
    char *array[9];

    while (p != NULL){
        array[i++] = p;
        p = strtok(NULL, " ");
    }
    return 0;
}

You can do this again to split it up even further. To explain what strtok does I shall explain with this code :

strtok(word, " ");. word is the content of the string that will be modified and " " with be the delimiter for the string.