简体   繁体   English

有关C ++中cin的问题

[英]A question about cin in C++

When I declare int weight and then input a double value 165.1 a 2nd cin >> height; 当我声明int weight ,然后输入一个双165.1165.1 ,第二个cin >> height; doesn't work and there is no any error message. 不起作用,没有任何错误消息。 Can you tell me why? 你能告诉我为什么吗?

VS2010 Console Application used. 使用了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.

If you try to have cin extract data into a variable that can't hold it, the data is left in the input stream and cin is flagged as having failed. 如果您尝试让cin数据提取到无法保存的变量中,则数据将保留在输入流中,并且cin被标记为失败。 You need to check if it's failed with !cin , and use cin.clear() to clear the fail flag so you can read again (future extract operations will automatically fail until the flag is cleared). 您需要使用!cin检查它是否失败,然后使用cin.clear()清除失败标志,以便您再次读取(将来的提取操作将自动失败,直到该标志被清除)。 You can either extract the data into a different variable that's capable of holding it, or use cin.ignore() to discard it 您可以将数据提取到一个可以保存数据的变量中,也可以使用cin.ignore()丢弃它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM