关于C++中cin的问题

Nan*_* HE 1 c++ cin

当我声明int weight然后输入一个double值时165.1,2nd 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.
Run Code Online (Sandbox Code Playgroud)

Mic*_*zek 13

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