[英]C: How can I store an unknown number of inputs using scanf so that each word of the input is stored in a different variable?
So far i have: 到目前为止,我有:
char r[4][10];
printf("Enter an option: \n");
scanf("%s %s %s %s %s", r[0],r[1],r[2], r[3], r[4]);
printf("%s %s %s %s %s\n", r[0], r[1], r[2], r[3], r[4]);
This works as long as 5 inputs are given. 只要给出5个输入,就可以使用。 Right now if you type less then 5 inputs and hit enter the program continues to ask for input until it has all 5 values but I want the scanf to stop and the program to continue if less then 5 inputs are entered. 现在,如果您键入的输入少于5个,然后按Enter键,程序将继续要求输入,直到它具有所有5个值,但是如果输入的输入少于5个,我希望scanf停止并且程序继续。
You'll do best to read a line with fgets()
and parse it with sscanf()
. 最好使用fgets()
读取一行,并使用sscanf()
对其进行解析。 If there will be no more than 5 words on a line: 如果一行上的单词数不超过5个:
char r[5][10];
char line[4096];
printf("Enter an option: \n");
if (fgets(line, sizeof(line), stdin) != 0)
{
int num = sscanf(line, "%9s %9s %9s %9s %9s", r[0],r[1],r[2], r[3], r[4]);
for (int i = num; i < 5; i++)
r[i][0] = '\0';
printf("%s %s %s %s %s\n", r[0], r[1], r[2], r[3], r[4]);
}
Note that you only had r[4][10]
but were using subscript 4 — bad move. 请注意,您只有r[4][10]
但使用的是下标4-错误的动作。
A better way to handle it would be a loop that scans over the line, reading a word at a time until there is no more space in the array or no more words in the line. 一种更好的处理方法是循环扫描整个行,一次读取一个单词,直到数组中没有空间或行中没有单词为止。 It's a little trickier, though. 不过,这有点棘手。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.