c ++循环永远运行而无需等待输入

时间:2013-06-09 22:53:01

标签: c++ loops cin

我正在尝试编写循环并将用户输入输入到类并打印出图表的代码。这是我的主要方法:

int main()
{
    Company productMatrix;
    int inputNumber = 0;
    cout << "enter the salesman id or -1 to quit." << endl;
    cin >> inputNumber;
    while(inputNumber != -1)
    {
        int salesman = inputNumber;
        cout << "enter the product id." << endl;
        cin >> inputNumber;
        int product = inputNumber;
         cout << "enter the amount sold." << endl;
        cin >> inputNumber;
        double dollarValue = inputNumber;
        productMatrix.inputSales(salesman, product, dollarValue);
        cout << "enter the salesman id or -1 to quit." << endl;
        cin >> inputNumber;
    }
    productMatrix.printChart();
    cout << "Goodbye!";
    return 0;
}

当我运行程序时,它会让我输入一组数据然后永远循环而不等我停下来。这就是它的样子:

enter the salesman id or -1 to quit.
3
enter the product id.
2
enter the amount sold.
55.99
enter the salesman id or -1 to quit.
enter the product id.
enter the amount sold.
enter the salesman id or -1 to quit.
enter the product id.
enter the amount sold.
// etc...

我猜我的循环有问题。我怎么能这个呢?

4 个答案:

答案 0 :(得分:2)

您正在为一个整数写一个双55.99,因此cin需要55,并且缓冲区中的'.'始终为!=-1但永远不会被读入作为整数。

答案 1 :(得分:2)

问题在于以下行。

double dollarValue = inputNumber;

inputNumber是整数类型,而美元值是浮点数。所以存在类型不匹配。您可以创建另一个变量,如dollarInput,并将美元值存储在那里

答案 2 :(得分:0)

inputNumberint。但是您输入的值(55.99)无法解释为int。这会将cin置于错误状态。在清除错误之前,cin以后的所有操作都将失败。所以它不会等待你的输入,并且变量保留它们的值,你永远不会得到循环需要终止的-1

要检查错误,只需使用普通的旧if语句:

if (cin) {
    // cin is okay
}
else {
    // cin is not okay
}

您还可以更简洁一点,将输入操作直接放在if语句中:

if (cin >> inputNumber) {

清除错误:

cin.clear();

您可能还需要清除输入流,否则错误输入将保留在输入缓冲区中,cin将尝试再次读取它:

cin.ignore(); // discard one character from the input buffer
// or
cin.ignore(N); // discard N characters from the input buffer

无论如何,这是无限循环的原因。但是,如果您只是直接输入double而不是int,则不会看到此问题。这不是你想要的吗?

答案 3 :(得分:0)

要添加到prajmus的答案,您可以通过添加以下'cin'读取来在输入流中看到额外的“垃圾”:

...
double dollarValue = inputNumber;
productMatrix.inputSales(salesman, product, dollarValue);
cout << "enter the salesman id or -1 to quit." << endl;

double myDbl;
cin >> myDbl;
cout << "read the following double:" << myDbl << endl;
...

添加的“cin&gt;&gt; myDbl”将从输入流中读取“.99”,添加的cout将会产生:

0.99