C-数字检查功能提供无限循环 [英] C- number checking function gives infinite loop

查看:75
本文介绍了C-数字检查功能提供无限循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个可以获取数字的小函数. 该功能应该是防白痴的,因此,如果出现警告,它将发出警告.有人输入了一个字符.

I'm trying to write a small function that will get a number. The function should be idiot-proof so it would give warnings if ie. someone entered a character instead.

我写了一个类似下面的函数,但是如果我输入一个非整数,程序会给我一个无限循环,不断重复printf不是有效数字",所以我永远都没有机会进行正确的输入.

I wrote a function like the one below, but if I enter a non-int the program gives me an infinite loop, constantly repeating the printf "Not a valid number" so I never get a chance to do the correct input.

代码:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    for (int ret = 0; ret < 1;)
    {
        int num;

        printf("\n Please input a number: ");
        ret = scanf ("%d", &num);
        if (ret < 1)
            printf ("\nNot a valid number!");
        else
            printf("\nYou input %d", num);
    }
    return 0;
}

如何解决?

推荐答案

请注意下面的行,其中包含有关吃掉输入缓冲区的注释.由于您的scanf在输入缓冲区中找不到所需的内容,因此错误的输入只会停留在该位置,并且永远失败,除非您执行某些操作以吃掉"它.

Note the line below with the comment about eating the input buffer. Since your scanf didn't find what it is looking for in the input buffer, the wrong input just stays there and fails forever unless you do something to "eat" it.

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    printf("Hello world!\n");
    while ('A')
    {
        int x, y;
        printf("\n x: ");

        y = scanf ("%d", &x);
        printf("\nx = %d", x);
        if (y < 1)
        { // eat the input buffer so we can try again
            while ( getchar() != '\n' );
            printf ("\nWRONG!");
        }
    }

    return 0;
}

这篇关于C-数字检查功能提供无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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