在此程序中,我采用了大小为 [3][4] 的维字符数组,
只要我每行输入 3 个字符,它就可以正常工作。
例如:如果我输入abc
abd
abd
我得到相同的输出,但如果我在第一行、第二行或第三行输入更多字母,则会出现错误。
我应该如何检查二维中的空字符?
# include <stdio.h>
#include <conio.h>
# include <ctype.h>
void main()
{
int i=0;
char name[3][4];
printf("\n enter the names \n");
for(i=0;i<3;i++)
{
scanf( "%s",name[i]);
}
printf( "you entered these names\n");
for(i=0;i<3;i++)
{
printf( "%s\n",name[i]);
}
getch();
}
正如@SouravGhosh 所指出的,你可以限制你的scanf
with "%3s"
,但是如果你不冲水,问题仍然存在stdin
在每次迭代中。
你可以这样做:
printf("\n enter the names \n");
for(i = 0; i < 3; i++) {
int c;
scanf("%3s", name[i]);
while ((c = fgetc(stdin)) != '\n' && c != EOF); /* Flush stdin */
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)