关于C ++中cin的问题

时间:2010-06-24 01:55:13

标签: c++ cin

当我声明int weight然后输入双值165.1时,第二个cin >> height;不起作用,并且没有任何错误消息。你能告诉我为什么吗?

使用VS2010控制台应用程序。

#include <iostream>

using namespace std;

const double lbs_to_kg = 2.2046, inches_to_meter = 39.370;

int main()
{
    int weight, height;
    double kilograms, meters;

    cout << "\nEnter weight in pounds: ";
    cin >> weight;
    kilograms = weight / lbs_to_kg;
    cout << "\nEnter height in inches: ";
    cin >> height;
    meters = height / inches_to_meter;
    cout << "\nYour BMI is approximately "
        << "\nbody fat ratio is "
        << kilograms / (meters * meters)
        << ". Under 25 is good."
        << endl;

}

output:

Enter weight in pounds: 165.1

Enter height in inches:
Your BMI is approximately
body fat ratio is 1.57219e-013. Under 25 is good.

1 个答案:

答案 0 :(得分:13)

如果您尝试将cin数据提取到无法保存的变量中,则数据会保留在输入流中,并且cin会被标记为失败。您需要使用!cin检查它是否失败,并使用cin.clear()清除失败标志,以便您可以再次读取(将来的提取操作将自动失败,直到标志被清除)。您可以将数据提取到能够容纳它的另一个变量中,或者使用cin.ignore()将其丢弃