繁体   English   中英

C++ While/do while 循环不会在 cin 上暂停

[英]C++ While/ do while loop not pausing on a cin

无论我似乎做什么,我都无法让代码在 cin 上暂停英尺或英寸。 我曾尝试使用 cin.clear 和 cin.ignore 但之前的 cin 是一个字符串

double inches = 0.0;
double feet = 0.0;

do 
{
    cout << "Please enter your height in feet:" << endl;
    cin >> feet;

    if  (feet > 2 && feet < 8)
    {
        cout << "Thank you!" << endl;
        break;
    }
    else if (feet < 2 || feet > 8)
    {
        cout << "You must be between 2 and 7 feet" << endl;
        
    }
} while (heightB);

while (heightB)
{
    cout << "\nPlease enter the inches:" << endl;
    cin >> inches;

    if (inches < 0 || inches > 11)
    {
        cout << "\nInches must be between 0 and 11" << endl;
    }
    else
    {
        cout << "Thank you!" << endl;
        break;
    }

}

total_inches = feet * 12 + inches;
cout << "Your total height in inches is: " << total_inches << endl;

解决了我自己的问题,结果问题从来没有出现在这个问题上。 由于对字符串缺乏经验,我犯了一个菜鸟错误。 在此之前,我使用了 cin >> name 作为字符串。 相反,我需要使用 getline(cin, name) 来获取所有文本。

因为我没有这样做,我的循环只是无休止地循环。

我稍微修改了您的代码以使其可执行,并且它按预期工作没有任何问题。

    #include<iostream>
    using namespace std;
    
    int main(){ 
        bool heightB = 1;
        double inches = 0.0;
        double feet = 0.0;
        double total_inches = 0.0;
        do 
        {
            cout << "Please enter your height in feet:" << endl;
            cin >> feet;
    
            if  (feet > 2 && feet < 8)
            {
                cout << "Thank you!" << endl;
                break;
            }
            else if (feet < 2 || feet > 8)
            {
                cout << "You must be between 2 and 7 feet" << endl;
                
            }
        } while (heightB);
    
        while (heightB)
        {
            cout << "\nPlease enter the inches:" << endl;
            cin >> inches;
    
            if (inches < 0 || inches > 11)
            {
                cout << "\nInches must be between 0 and 11" << endl;
            }
            else
            {
                cout << "Thank you!" << endl;
                break;
            }
    
        }
        
        total_inches = feet * 12 + inches;
        cout << "Your total height in inches is: " << total_inches << endl;
        
        return 0;
    }

暂无
暂无

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

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