如何使用scanf限制输入长度 [英] How to limit input length with scanf

查看:1108
本文介绍了如何使用scanf限制输入长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此程序中,我采用尺寸为[3] [4],
的三维字符数组,只要我为每行输入3个字符,它将很好用。

In this program I have taken a dimensional character array of size[3][4], as long as I enter a 3 characters for each row it will work well.

例如:如果我输入 abc abd abd 我得到相同的输出,但是如果我在第一行,第二行或第三行中输入更多字母,则会出现错误。

For example: if I enter abc abd abd I get the same output but if i enter more letters in the first or second or 3rd row I get an error.

我应该如何检查null

How should I check for null character in 2 dimensional?

# 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 限制为%3s ,但是问题是如果您在每次迭代中不刷新 stdin 仍会存在。

As pointed out by @SouravGhosh, you can limit your scanf with "%3s", but the problem is still there if you don't flush stdin on each iteration.

您可以执行以下操作:

    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 */
    }

这篇关于如何使用scanf限制输入长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆