为什么这个程序无限循环?

时间:2012-03-22 11:27:50

标签: c++

我有这样一个程序:

#include <stdlib.h>
#include <iostream>

static int pswd=0;

int main() {

    do {
        std::cout<<"I need your password:"<<std::endl;          
        std::cin>>pswd;
    } while (pswd!=3855);

    std::cout<<"Congratulations! Your password is correct! Your soul is free again!"<<std::endl;
}

我可能是一个愚蠢的问题。 当我输入无效值(非数字符号或大于int的值)时,程序进入无限循环而不从控制台读取任何信息。

I need your password:
I need your password:
I need your password:
I need your password:
I need your password:
I need your password:
I need your password:
I need your password:
I need your password:
I need your password:
I need your password:
I need your password:
I need your password:
I need your password:
I need your password:
I need your password:
I need your password:
I need your password:
I need your password:
I need your password:
I need your password:
I need your password:
I need your password:
I need your password:
        ...

为什么这个程序会无限循环?

3 个答案:

答案 0 :(得分:10)

因为输入无效后,流处于失败状态,所有进一步的输入操作都是无操作。您始终必须检查输入操作的结果。

do {
    std::cout<<"I need your password:"<<std::endl;          
    if (!(std::cin >> pswd)) {
        // clear error flags
        std::cin.clear();
        // discard erroneous input (include <limits>)
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    }
} while (pswd!=3855);

答案 1 :(得分:1)

它正在尝试读取int,但它可以从STDIN查看缓冲区。它注意到您没有int,因此cin>>失败。 (见fail bit)。

所以它再次出现。您需要检查失败的类型转换。

答案 2 :(得分:1)

我很确定你想在这里阅读一个字符串,因为没有什么可以控制用户输入的内容。

您想要读入char缓冲区(下面的缓冲区支持256个字符),然后使用strcmp将其与您要查找的密码进行比较:

#include <stdlib.h>
#include <iostream.h>

static int pswd=0;
static char buffer[256];

int main()
{
    do
    {
        std::cout<<"I need your password:"<<std::endl;          
        std::cin>>buffer;
    }
    while (strcmp("3855", buffer));
    std::cout<<"Congratulations! Your password is correct! Your soul is free again!"<<std::endl;
}

请注意,strcmp在两个字符串匹配时返回0。