rdvl0 rdvl0 - 4 months ago 15
C Question

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

Answer

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