簡體   English   中英

c++ 任務在 while 循環后不會執行

[英]c++ task won't execute after while loop

C++ 新手在這里。 我不確定如何描述這一點,但while-loop之外的任務不會立即執行。 我需要再次輸入輸入值才能完成。 這是我的代碼:

#include <iostream>
using namespace std;

int main()
{

    int fourDigitInt, firstDigit, secondDigit, thirdDigit, fourthDigit, i = 0;

    cout << "Enter a 4-digit integer  :  ";
 
    cin >> fourDigitInt;


    while (fourDigitInt > 9999 || !(cin >> fourDigitInt))
    {

        i++;
        if (i >= 3)
        {
            cout << "You do not seem to understand the program instruction.\nPlease try again later." << endl;
            return -1;
        }
        else
        {

            cout << "Error: Please make sure you are entering a 4-digit integer" << endl;
            cin.clear();
            cin.ignore(4, '\n');
            cout << "Enter a 4-digit integer  :  ";
        }
    }

    firstDigit = fourDigitInt / 1000 % 10;

    secondDigit = fourDigitInt / 100 % 10;

    thirdDigit = fourDigitInt / 10 % 10;

    fourthDigit = fourDigitInt / 1 % 10;

    cout << "1st digit  :  " << firstDigit << endl;
    cout << "2nd digit  :  " << secondDigit << endl;
    cout << "3rd digit  :  " << thirdDigit << endl;
    cout << "4th digit  :  " << fourthDigit << endl;
}

以下是我遇到的一些問題:

1)如果我先輸入一個string ,它沒有任何問題。 2)但是如果我輸入任何小於9999的數字,除非我再次輸入,否則它不會執行計算。 3)如果我輸入一個 5 位數字, endl將不起作用。 它只會顯示Enter a 4-digit integer: Error: Please make sure you are entering a 4-digit integer ,這應該是不同的行。

我到底哪里做錯了? 先感謝您。

這里的主要問題是while循環條件。 它應該只檢查fourDigitInt變量的值,因為這很重要。

仔細觀察,您還可以注意到循環內的if case 將檢查第二次迭代而不是第三次的事實。 我也通過在else塊中移動i++來解決這個問題。

while (fourDigitInt > 9999 || fourDigitInt < 1000){ 
    if (i >= 3){ 
        cout << "You do not seem to understand the program (ironic coming for OC) instruction.\nPlease try again later." << endl;
        return -1;
    }
    else {
        i++;
        cout << "Error: Please make sure you are entering a 4-digit integer" << endl;
        cout << "Enter a 4-digit integer  :  ";
        cin >> fourDigitInt;
    }
}

您的代碼可能出現的任何其他問題與此問題無關。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM