c++ - while 循环不提示用户输入 (c++)

标签 c++ arrays loops input

我的循环工作正常,直到我输入最后一个值作为性别的输入,当输入“true”时,循环忽略其余循环的 cin,只打印 cout 中的文本,直到循环结束,任何想法如何让循环在每个循环上都要求输入,或者我在哪里犯了错误? ps:这是一项功课,所以我无法更改给出的结构。感谢您的任何建议。代码片段:

int main()
{
    struct Patient
    {
        double height;
        double weight;
        int age;
        bool isMale;
    };
    Patient ListOfPatients[4];
    int iii = 0;

    while (iii < 4)
    {
        cout << "enter the height (eg. 1.80 metres) of patient number  " << iii + 1 << " :" << endl;
        cin >> ListOfPatients[iii].height;
        cout << "enter the weight (eg. 80kg) of patient number " << iii + 1 << " :" << endl;
        cin >> ListOfPatients[iii].weight;
        cout << "enter the age of patient number " << iii + 1 << " :" << endl;
        cin >> ListOfPatients[iii].age;
        cout << "is the patient a male? (true = male or false = female) " << endl;
        cin >> ListOfPatients[iii].isMale;

        iii++;
    }

    return 0;
}

最佳答案

问题是当您阅读 isMale 时. bool确实是一个数字,0对于 false , 1对于 true .您无法将字符串读入其中。

发生的情况是,您最终在流中得到了一堆字符,这些字符无法被任何 >> 读取。操作,所以它们都连续失败。尝试传入 10在命令行上,一切正常。

如果您希望用户能够传入一个字符串,然后将其视为 bool ,您可以使用专门为此提供的实用程序,或手动执行此操作以帮助您理解。

要使用标准实用程序,它称为 std::boolalpha并出现在 <iomanip> header :

std::cin >> std::boolalpha >> ListOfPatients[i].isMale;

要手动执行此操作,请将其读入 std::string反对并自己做一些比较,就像这样:

std::string tmpIsMale;
std::cin >> tmpIsMale;
ListOfPatients[i].isMale = (tmpIsMale == "true");

正是出于这个原因,在尝试读取流后检查流的状态也是一个好主意。您可以将流直接放入 if为此:

std::cin >> someVariable;
if (!cin) { // cin is not in a good state
    std::cerr << "Failed to read someVariable, please try again with a proper value!\n";
    return 1;
}

您可能希望避免的一些旁白和不良做法:

  1. using namespace std; 被广泛认为是不好的做法。
  2. std::endl 有点争议,但您使用它的方式表明您不理解它。
  3. 性别不是 bool 值选项。我知道这不是一个严格的技术问题,如果结构是由你的老师提供的,你就有点卡住了,但是拜托,现在是 2019 年了!学习编写好的程序并不仅仅意味着语言的技术细节,还包括学习如何编写对用户有益的程序,所以尽早养成良好的习惯是个好主意。

关于c++ - while 循环不提示用户输入 (c++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55124887/

相关文章:

c - 为什么我的程序不会停止循环?

c++ - 当小部件被遮挡和未被覆盖时,如何避免调用paintevent()

javascript - 对同一个数组运行两个 for 循环

python - 如何将 2d 列表转换为 2d native python 数组而不是 numpy 数组?

JavaScript - 相同行和列中值的总和

c - 使用 'for' 循环为变量赋值并在该函数中使用变量名称

c++ - 是否可以在一个 visual studio c++ 项目中使用同名源文件?

C++ "if then else"模板替换

C++重载函数名查找错误

arrays - 如何在一次迭代中找到数组中的第二个最大元素?