简体   繁体   中英

In C, is there a way to take multiple user inputs from one line command line prompt?

I'm wondering in C is there a way to prompt the user to enter 2 different values, and then store those two values separately, all in one user entry. For example:

Enter your age and blood type : 34 AB

Then we store the two enties separately like

fgets(string,string, 64, 64, stdin);

Clearly THIS won't work, but is there a way possible in C. I'm very new to C (2 days). I know in Java you can use the args[] defined in the main and grab command line entries by index, where each space in the user's input would be a different element in the args array.

args in main works in C too, though the conventional name is argv (argument vector), as in int main(int argc, char **argv) .

You can also use scanf, as in scanf("%d %s", &age, blood_type); .

A third, and usually recommended way when processing user input, is to separate input from analyzing the input, as in:

fgets(line, sizeof line, stdin);
sscanf(line, "%d %s", &age, blood_type);

A more complete version of the above code, with error checking:

char line[100];
int age;
char blood_type[100];
if (fgets(line, sizeof line, stdin) == NULL ||
    sscanf(line, "%d %s", &age, blood_type) != 2) {
    fprintf(stderr, "Couldn't read age and blood type. Sorry.\n");
    exit(EXIT_FAILURE);
}

Since line contains at most 99 characters, plus the '\\0' that marks the end of the string, we cant get an overflow in the variable blood_type . Otherwise, we could use %99s instead of just %s to limit the number of characters that can be put into blood_type .

The best way by far is

char string[100];

if (fgets(string, sizeof(string), stdin) != NULL) {
    // split the string here to extract the "n" values
}

另外一个选项(取决于您的环境) getopt

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