Boyan Kushlev
Boyan Kushlev

Reputation: 1053

Do-while loop does not end?

I have the weirdest problem! I need to make a program where the user has to input a 10-digit number. So I check the input with a do-while loop:

do
{
    cout<<"Enter a 10-digit number: "<<endl;
    cin>>number;
} 
while (numberOfDigits(number) != 10);

Here is the numberOfDigits function:

    int numberOfDigits(int num)
    {
        int d = 0;

        while (num > 0)
        {
            num /= 10;
            d++;
        }

        return d;
    }

So when I enter a number less than 10, it loops and goes to the start (telling me to input a 10-digit number again). However, when I input a number with more than 10 digits, an infinite loop occurs, and the console doesn't stop printing "Enter a 10-digit number: "... Any ideas?

Upvotes: 1

Views: 939

Answers (2)

Mick
Mick

Reputation: 27

If you changed

while (numberOfDigits(number) != 10)

to

while (numberOfDigits(number) <= 10)

this way it would continue the do-while loop till the user had selected a number that is less that or equal to.

Upvotes: 0

marsh
marsh

Reputation: 2720

My guess would be that you are going past the max range of a int. If you are typing a number in that is higher then 2,147,483,647 which is extremely likely considering you need 10 numbers. Try using a long long.

int numberOfDigits(long long num)
{
    long long d = 0;

    while (num > 0)
    {
        num /= 10;
        d++;
    }

    return d;
}

I just tried it and it works fine for me. Full program I used to test:

using namespace std;

int numberOfDigits(long long num)
{
    long long d = 0;

    while (num > 0)
    {
        num /= 10;
        d++;
    }

    return d;
}

int main()
{
    long long number = 0;
    do
    {
        cout<<"Enter a 10-digit number: "<<endl;
        cin>>number;
    } 
    while (numberOfDigits(number) != 10);
    return 1;
}

Upvotes: 3

Related Questions