C值检查函数给出无限循环

编程入门 行业动态 更新时间:2024-10-23 07:39:01
本文介绍了C值检查函数给出无限循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我这里有一个小菜鸟问题。 我正在尝试编写一个能获得数字的小函数。 该功能应该是防止傻瓜的,所以它会发出警告。有人输入了一个字符。

I have a small noob question here. 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.

我写了一个类似下面的函数,但如果我输入一个非int程序给我一个无限循环,不断重复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; }

我知道有一种简单的方法可以修复它,我简直记不起来了一。花了最后两个小时试图搞清楚。 请帮助。

I know there's a simple way to fix it, I just can't recall one. Spend last two hours trying to figure it out. Please help.

推荐答案

请注意下面的行以及关于吃输入缓冲区的注释。由于你的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值检查函数给出无限循环

本文发布于:2023-10-31 06:02:05,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1545225.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!