【问题标题】:%d placeholder input '3abc', cannot clear 'abc' buffer%d 占位符输入“3abc”,无法清除“abc”缓冲区
【发布时间】:2017-05-25 11:53:42
【问题描述】:

下面是我的代码:

int length;
char ch;

printf("\n\tEnter the length of the password: ");
while (scanf("%d", &length) != 1) {

    printf("\n\tPlease enter digit only.\n");
    printf("\n\tEnter the length of the password: ");

    while ((ch = getchar()) != '\n' && ch != EOF);
}

printf("\n\tEnter the number of passwords you want: ");
while (scanf("%d", &num) != 1) {

    printf("\n\tPlease enter digit only.\n");
    printf("\n\tEnter the number of passwords you want: ");

    while ((ch = getchar()) != '\n' && ch != EOF);
}

当我输入abc 好的时候。

当我输入3abc时,按长度收到3,但'abc'仍在缓冲区中。

我用while ((ch = getchar()) != '\n' && ch != EOF);清除了还是不行?

感谢专家的任何帮助。

【问题讨论】:

  • 您是否将ch 声明为int
  • char ch;
  • 识别ch != EOF ch 必须是 int...
  • getchar 返回 int 类型。见原型:int getchar(void)
  • 或者注释不是指你要问的问题,而是你代码的问题之一。

标签: c buffer stdin flush


【解决方案1】:

如果scanf() 成功,则不会执行循环内的内容...所以如果您输入“3abc”,scanf() 会读取“3”,而“abc”仍在输入缓冲区中,因为您没有'不要进入循环

【讨论】:

    【解决方案2】:

    如果scanf 正确抓取了一个数字作为您的测试用例3asc,则您不会刷新stdin

     int length;
     int ch;
    
     printf("\n\tEnter the length of the password: ");
     while (scanf("%d", &length) != 1) {
    
         printf("\n\tPlease enter digit only.\n");
         printf("\n\tEnter the length of the password: ");
    
         while ((ch = getchar()) != '\n' && ch != EOF);
     }
    
     // flush stdin
     while ((ch = getchar()) != '\n' && ch != EOF);
    
     printf("\n\tEnter the number of passwords you want: ");
     while (scanf("%d", &length) != 1) {
    
         printf("\n\tPlease enter digit only.\n");
         printf("\n\tEnter the number of passwords you want: ");
    
         while ((ch = getchar()) != '\n' && ch != EOF);
     }
    

    并且,已经评论过,要识别ch != EOF ch 必须是 int。另外getchar原型是int getchar(void)

    【讨论】:

    • 建议的答案不起作用。当用户输入#...#... 时,两个循环之间stdin 的清除将消耗第二个数据项。不是想要的。
    • @user3629249 首先,感谢您对您的 DV 的评论:现在已经很少见了。第二:谁告诉你预期的行为是你猜测的?据我们所知,OP 要求接受每个换行符一个输入,这就是 OP 通过我提出的(并接受的)解决方案实现的。
    • 我可能误读了 OP 的这句话:当我输入 3abc 时,按长度接收 3,但 'abc' 仍在缓冲区中。 表示整个内容都在一行中输入(OP 发布的代码允许这样做。)
    猜你喜欢
    • 2013-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多