【发布时间】:2014-09-18 04:57:07
【问题描述】:
我有一个简单的程序来输入 5 个字符串的数组并输出它们。但是输出有些奇怪。以下是我的代码。
#include <stdio.h>
int main()
{
char a[10][5];
int i;
for(i=0; i<5; ++i)
{
printf("\nEnter the name of %d st student:", i+1);
fflush(stdout);
gets(a[i]);
}
for(i=0; i<5; ++i)
{
printf("\n%s", a[i]);
fflush(stdout);
}
return 0;
}
我将输入作为 tom、john、peter、david 和 alan 给出,我得到以下输出。
tom
john
peterdavidalan
davidalan
alan
可能是什么问题?
【问题讨论】:
-
char a[10][5]有 10 个字符串的空间,每个字符串最多 4 个字符。尝试char a[5][10] = {0};5 个字符串,每个字符串最多 9 个字符,初始化为零。 -
永远不要使用
gets:这是一个非常糟糕的缺陷,它在C11之前被弃用,然后被禁止。 -
@Deduplicator 而
scanf("%s", buf);仍然存在