如何使用scanf限制输入长度

ven*_*kat -3 c arrays scanf

在这个程序中,我采用了一个大小为[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(); 
}
Run Code Online (Sandbox Code Playgroud)

Dav*_*eri 5

正如@SouravGhosh 所指出的,您可以限制您的scanfwith "%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 */
}
Run Code Online (Sandbox Code Playgroud)