Home > Mobile >  c task won't execute after while loop
c task won't execute after while loop

Time:08-12

C newbie here. I'm not sure how to describe this but the task outside of the while-loop won't execute immediately. I need to enter the input value again to get it done. Here is my code:

#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;
}

Here are some problems I encountered:

1)If I enter a string first, it doesn't have any problem. 2)But if I enter any number less than 9999, it won't execute the calculation unless I enter it again. 3)If I enter a 5-digit number the endl won't work. It will just display Enter a 4-digit integer : Error: Please make sure you are entering a 4-digit integer which suppose to be a different line.

Where exactly did I do wrong? Thank you in advance.

CodePudding user response:

The main issue here is in the while loop condition. It should just check for the value of the fourDigitInt variable as that is what is important.

Looking closer, you will also be able to notice the fact that the if case inside of the loop would check for the second itteration instead of the third. I fixed that as well by moving the i inside of the else block.

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;
    }
}

Any other issues with your code that may occur are not related to this question.

  •  Tags:  
  • c
  • Related