在C中,有没有办法从一行命令行提示中获取多个用户输入?

Elr*_*son 0 c unix

我想知道在C中有没有办法提示用户输入2个不同的值,然后分别存储这两个值,所有这些都在一个用户条目中.例如:

Enter your age and blood type : 34 AB
Run Code Online (Sandbox Code Playgroud)

然后我们分别存储两个内容

fgets(string,string, 64, 64, stdin);
Run Code Online (Sandbox Code Playgroud)

很明显,这不会起作用,但在C中是否有可能.我对C很新(2天).我知道在Java中你可以使用main和grab命令行条目中定义的args [],其中用户输入中的每个空格都是args数组中的不同元素.

Tho*_*thy 8

args在C的主要工作中,虽然传统的名称是argv(参数向量),如int main(int argc, char **argv).

您也可以使用scanf,如scanf("%d %s", &age, blood_type);.

处理用户输入时,第三种(通常是推荐的方法)是将输入与分析输入分开,如:

fgets(line, sizeof line, stdin);
sscanf(line, "%d %s", &age, blood_type);
Run Code Online (Sandbox Code Playgroud)

上述代码的更完整版本,带有错误检查:

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);
}
Run Code Online (Sandbox Code Playgroud)

由于line包含最多99个字符,加上标记字符串结尾的'\ 0',我们无法在变量中获得溢出blood_type.否则,我们可以使用%99s而不是仅%s限制可以放入的字符数blood_type.