簡體   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