[英]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. 我想知道在C中是否有一种方法可以提示用户输入2个不同的值,然后分别将这两个值存储在一个用户条目中。 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). 显然,这是行不通的,但是在C语言中是否有可能。我对C语言非常陌生(2天)。 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. 我知道在Java中,您可以按索引使用main和抓住命令行条目中定义的args [],其中用户输入中的每个空格将是args数组中的不同元素。
args
in main works in C too, though the conventional name is argv
(argument vector), as in int main(int argc, char **argv)
. args
可以在C语言的argv
,尽管常规名称是argv
(参数向量),例如int main(int argc, char **argv)
。
You can also use scanf, as in scanf("%d %s", &age, blood_type);
您也可以使用scanf,如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
. 由于line
最多包含99个字符,加上标记字符串结尾的'\\ 0',因此我们无法在blood_type
变量中blood_type
。 Otherwise, we could use %99s
instead of just %s
to limit the number of characters that can be put into blood_type
. 否则,我们可以使用%99s
而不是仅使用%s
来限制可以放入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
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.