在while语句无限循环 [英] Infinity loop in while statement

查看:170
本文介绍了在while语句无限循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我的code片段

Here is a snippet from my code

scanf("%d", &s);

while(s!=1 && s!=2) {
    if(scanf("%d", &s) != 1) {
        show_warning(); //just print some info msg
    }
}

的想法是要执行show_warning功能仅当用户输入的东西的1,2-不同和输入值是唯一整数。
随着code它上面跳跃无限循环。如何解决呢?

The idea is to execute show_warning function only if user enter something different of 1,2 and entered value to be only integer. With the code above it jumps in infinity loop. How to fix that ?

推荐答案

的问题是,失败的输入操作不从流中提取任何字符(你会继续一遍遍读无效输入),所以您必须手动清空输入。例如:

The problem is that the failed input operation doesn't extract any characters from the stream (and you'll keep reading the invalid input over and over), so you have to empty the input manually. For example:

char buf[1000];

// ...

if(scanf("%d", &s) != 1)
{
    puts("Error, try again: ");
    fgets(buf, 1000, stdin);
}

我在等问题的,如果你使用与fgets 从一开始就始终读取一行,以后再处理它,你克服这个问题。

As I suggested in the other question, if you use fgets from the start to always read one line and process it later, you overcome this problem.

(同样的理念是在C ++中真正的:先读整行,以便输入流可以继续前进,并处理线后,看其是否有效)

(The same philosophy is true in C++: read the whole line first so the input stream can move on, and process the line later to see if its valid.)

这篇关于在while语句无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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