Abhinav Abhinav - 23 days ago 10
C Question

Do while loop with choice as char in C

In my code given below if I press 'y' for once it will reapeat, but then it is not asking for next tome to repeat (or press 'y').Can someone help why this code is terminated after one loop?

main()
{
char choice;

do
{
printf("Press y to continue the loop : ");
scanf("%c",&choice);
}while(choice=='y');

}

Answer

That will be because stdin is buffered. So you are probably entering the string of a y followed by a \n (newline character).

So the first iteration takes the y, but the next iteration doesn't need any input from you because the \n is next in the stdin buffer. But you can easily get around this by getting scanf to consume the trailing whitespace.

scanf("%c ",&choice);

NOTE: the space after the c in "%c "

But, your program can get stuck in an infinite loop if the input ends with a y. So you should also check the result of the scanf. e.g.

if( scanf("%c ",&choice) <= 0 )
    choice = 'n';