rdvl0
rdvl0

Reputation: 15

Do-while loop keeps repeating

Can you please tell me why this loop keeps repeating without letting me read n?

int n;
do
{
    printf("Height: ");
    scanf("%d",&n);
}
while(n < 0 || n > 23);

I can't enter any value because "Height: " keeps repeating. Here's the full code:

#include <stdio.h>
#include <stdlib.h>
int main()
{
    int n,i,j,k;
    do
    {
        printf("Height: ");
        scanf("%d",&n);
    }
    while(n < 0 || n > 23);

    for(i=0;i < n;i++)
    {
        for(j=0;j < n - i - 1;j++)
        {
            printf("%c",' ');
        }
        for(k=0;k < i + 2;k++)
        {
            printf("%c",'#');
        }
        printf("\n");
    }
}

Upvotes: 1

Views: 544

Answers (2)

user3121023
user3121023

Reputation: 8308

Check the return of scanf. In this case if scanf is successful, it will return 1. If it does not return 1 then an invalid input was made such as www for an int. In that case, clear the buffer and try again.

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int i = -1;

    do {
        printf ( "height \n");
        if ( scanf ( "%d", &i) != 1) {// != 1 means scanf failed
            while ( ( i = getchar()) != '\n' && i != EOF) {
                ;//clear buffer
            }
            i = -1;
        }
    } while ( i < 0 || i > 23);

    return 0;
}

Upvotes: 3

Mike Horstmann
Mike Horstmann

Reputation: 588

Well if your value for n is greater than 23, that loop will print on forever. I'm also wondering if your first conditional n < 0 is providing the condition "is false" or "is greater than 23." You should try logging n to see what it's being provided to your loop as, and if it's greater than 23, maybe set an upper bounds for your loop.

Upvotes: 0

Related Questions