当我给 scanf() 一个非数字作为输入时,如何继续循环? [英] How can I continue the loop when I give scanf() a non-digit as input?

查看:43
本文介绍了当我给 scanf() 一个非数字作为输入时,如何继续循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想出了一个简单的例子.在这里它将从用户那里获取整数值并显示该值.当我输入字符而不是整数时,我想再次跳过该过程询问用户输入.为此,我在下面的代码中编写了此代码,但是当我输入字符时,它将继续循环,但在继续时,它不会向用户询问输入.请给出解决方案.

I worked out the simple example. Here it will get the integer value from the user and display the value. When I am giving a character input instead of an integer, I want to skip the process and again ask the user for input. For that, I wrote this below code, but when I give a character input it will continue the looping, but while continue it will not ask a input to user. Please give a solution for that.

 #include <stdio.h>

 int main()
 {
    int n;
    while(1){
            if(scanf("%d",&n)==0){
                    printf("Error:Checkyour input\n");
                    continue;
            }
            printf("the  input =%d\n",n);
    }
 }

输出如下:

  Error:Checkyour input
  Error:Checkyour input
  Error:Checkyour input
  Error:Checkyour input
  Error:Checkyour input
  Error:Checkyour input

推荐答案

这是因为 ENTER 键按下 [a \n] 存储在输入缓冲并不断向 [next] scanf() 提供错误输入.

This is happening because, the ENTER key press [a \n] is stored in the input buffer and continuously provides the wrong input to [next] scanf().

对您的代码进行以下更改.

make the following changes to your code.

 #include<stdio.h>

 int  main()                          //add the return type.

  {
    int n;
    while(1){
            if(scanf(" %d",&n)==0){
                    while (getchar() !='\n');   //eat up all the _invalid_ input present in input buffer till newline
                    printf("Error:Check your input\n");
                    continue;
            }
            printf("the  input =%d\n",n);
    }
    return 0;                      //add the return value.

 }

关于 Jonathan Leffler 先生的评论,请在下面找到更优化的代码版本, 还要处理 EOF.

In regards to Mr. Jonathan Leffler's comment, please find below a more optimized version of the code, taking care of EOF also.

 #include<stdio.h>

 int  main()

  {
    int n;
    int retval = 0;
    while(1){
            retval = scanf(" %d",&n);

            if (retval ==1)
                     printf("the  input =%d\n",n);
            else if (retval == 0)
            {
                    while (getchar() !='\n');
                    printf("Error:Check your input\n");
                    continue;
            }
            else                          //includes EOF case
                break;

    }
    return 0;

 }

这篇关于当我给 scanf() 一个非数字作为输入时,如何继续循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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