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

时间:2019-03-12 15:13:43

标签: 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;
}

1 个答案:

答案 0 :(得分:2)

您不能将字符串true分配给布尔字段。请检查更正的示例。

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

    while (iii < 4)
    {
        string sIsMale = "";

        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 >> sIsMale;
        ListOfPatients[iii].isMale = sIsMale == "true";

        iii++;
    }

    return 0;
}