使用scanf读取字符串数组? [英] Reading an array of strings using scanf?
问题描述
所以我有这个任务需要从标准输入读取4个字符的字符串到数组中。我试过一种方法,但每次我尝试打印这个数组的任何元素时,它总是从输入中打印出最后一个。例如输入:
abcd
dcba
aaaa
...
zzzz(第20个字符串)
printf(%s,arrayString [3]);
输出:
zzzz
有谁可以解释为什么它的工作原理是什么?
我尝试过:
So I've got this task that requires reading 4-character strings from standard input into an array. I tried one way but every time i tried printing any element of this array it always printed the last one from input. For instance input:
abcd
dcba
aaaa
...
zzzz (the 20th string)
printf("%s",arrayString[3]);
Output:
zzzz
Could anyone explain why is it working the way it is?
What I have tried:
char *stringArray[20];
char temp[4];
int i;
for(i=0;i<20;i++){
scanf("%s",temp);
stringArray[i]=temp;
}
推荐答案
你有一个包含20个字符串指针的数组。
每个都指向相同的内存(temp
)。
因为它用于读取用户输入在一个循环中,它包含最后一个输入字符串。
您可以使用二维数组:
You have an array of 20 string pointers.
Each of these points to the same memory (temp
).
Because that is used for reading the user input within a loop, it contains the last input string.
You can use a two-dimensional array instead:
char stringArray[20][5];
int i;
for (i=0;i<20;i++)
{
scanf("%4s", stringArray[i]);
}
请注意,我增加了输入字符串大小(必须总有一个字符来存储终止 NULL
字节)和将此限制添加到 scanf
格式字符串。
Note that I have increased the input string size (there must be always one more character to store the terminating NULL
byte) and added that limit also to the scanf
format string.
这篇关于使用scanf读取字符串数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!