使用 scanf 的返回值验证输入不起作用 [英] Validating input using scanf's return value isn't working

查看:37
本文介绍了使用 scanf 的返回值验证输入不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个井字游戏的最终项目.我让用户打印他想要填写的框号,然后我使用整数err 来获取scanf 的返回值.在这种情况下,Scanf 应该返回它读取的整数数量,我要求读取一个整数,所以只要 err != 1,它就应该进入 while 循环.但是,这不起作用.

I'm working on a tic-tac-toe final project. I ask the user to print the box number he would like to fill in, and then i use integer err to obtain the return value of scanf. Scanf should return the number of integers it has read in this case, and I am asking for one integer to be read, so as long as err != 1, it should go into the while loop. This, however, isn't working.

        printf("\nBox number: ");
        int boxNumber, err;
        err = scanf("%d", &boxNumber);

        while (err != 1) {
            printf("\nWrong input.");
            printf("\nBox number: ");
            err = scanf("%d", &boxNumber);
        } 

当输入一个非整数时,输出为:

When a non-integer is inputted, the output is:

输入错误.
箱号:

Wrong Input.
Box number:

在一个不停的循环中.然后再次调用 scanf 以供用户输入值的行就好像从未运行过一样.
我不知道问题是什么.请帮忙.

In a non-stop loop. The line where scanf is then called again for the user to input a value is as though never run.
I have no idea what the problem is. Please help.

推荐答案

在第一个 scanf() 失败后,非整数保留在输入流中并阻止任何后续成功,同时保持永远.

After the first scanf() fails, the non-integer remains in the input stream and prevents any following from succeeding, while staying forever.

您需要摆脱不可扫描的延迟输入.

You need to get rid of the non-scannable lingering input.

请参阅这些文章以选择您喜欢的方法:
http://sekrit.de/webdocs/c/beginners-guide-away-from-scanf.html
如何在 C 中读取/解析输入?常见问题解答

See these articles for choosing your favorite method:
http://sekrit.de/webdocs/c/beginners-guide-away-from-scanf.html
How to read / parse input in C? The FAQ

这篇关于使用 scanf 的返回值验证输入不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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