为什么我的程序在 For 循环的第一个周期后跳过 cin >>?

Why Is My Program Skipping The cin > > after the first cycle of the For Loop?

我的程序正确运行了第一个 For 循环,然后在第二个和第三个循环中跳过了 Cin。然后,当循环完成后,它继续计算第一个索引 [0] 的 BMI,并正确执行此操作并给出正确答案,但索引的 1 和 [2] 没有任何信息,因为没有输入任何信息,因为cin 被跳过了。

#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;

struct Patient
{
  double height;
  double weight;
  int age;
  bool isMale;
};


int main()
{
Patient Patients[3];

for (int i = 0; i < 3; i++) {
    cout << "Patient "<< i << " Height: ";
    cin >> Patients[i].height;
    cout << "Patient " << i << " Weight: ";
    cin >> Patients[i].weight;
    cout << "Patient " << i << " Age: ";
    cin >> Patients[i].age;
    cout << "Is Patient " << i << " Male True or False: ";
    cin >> Patients[i].isMale;
    cout << endl << endl;

   }

    cout << endl << endl;

    for (int i = 0; i < 3; i++) {
        float BMI = Patients[i].weight / (Patients[i].height *Patients[i].height);
        cout << "Patient " << i << " Has A BMI of: " << BMI << endl << endl;
      }

return 0;
 }

这是控制台,您可以在第一个循环后看到所有 cin 都被跳过,但第一个循环已正确存储,因为它计算了第一个索引的 BMI:

您可以通过两种方式修复您的程序。

  1. 只需在 male/female 问题中输入“0”或“1”,而不是 "true" 或 "false"。
  2. 改这一行,继续输入"true"或"false":

    cin >> boolalpha >> Patients[i].isMale;
    

来源:

Cin and Boolean input

http://www.cplusplus.com/reference/ios/boolalpha/

您看到在循环结束时出现错误。您可以从迭代 2 和 3 中看到 cin 每次的行为方式都不相同。来自 ios 的几个错误状态标志将帮助您了解这里出了什么问题。有关详细信息,请参阅 iso::good。如果您添加这些检查:

for (int i = 0; i < 3; i++) {
cout << "Patient " << i << " Height: ";
cin >> Patients[i].height;
cout << "Patient " << i << " Weight: ";
cin >> Patients[i].weight;
cout << "Patient " << i << " Age: ";
cin >> Patients[i].age;
cout << "Is Patient " << i << " Male True or False: ";
cin >> Patients[i].isMale;
cout << cin.good() << '\n';
cout << cin.eof() << '\n';
cout << cin.fail() << '\n';
cout << cin.bad() << '\n';
cout << endl << endl;
}

如果 cin 不再是 good,它不是 eof,而是 fail,而不是 bad,您会看到什么.当设置了 fail 位时,cin 将不起作用。因此你看到了结果。查看 link 中的图表,您会看到:

Logical error on i/o operation

您正在执行将 "true" 插入 bool 的 i/o 操作。 true 一词可能存储为字符数组或字符串,而不是布尔值。 cin 应该如何将其转换为布尔值?您需要捕获您的输入并将其转换为 bool 或切换为使用可以显式转换为 bool.

的输入

例如:

cout << "Is Patient " << i << " Male? (1 for Male, 0 for Female):";
cin >> Patients[i].isMale;

在这种情况下,cin10 识别为整数,并且可以将整数转换为布尔值。 0 为假,其他均为真。另一种选择是让库执行并使用 boolalpha。你可以阅读它 here.

这说明了一个更大的问题。如果我写 "two point five" 作为高度的答案会怎样?在这种情况下,我们可以假设用户有一定的智能,但考虑这样的事情将有助于将来编写更健壮的代码。