Abhinav
Abhinav

Reputation: 553

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');

}

Upvotes: 0

Views: 38511

Answers (3)

Sodved
Sodved

Reputation: 8588

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

Upvotes: 3

Lundin
Lundin

Reputation: 213458

At the first character of the scanf format string, insert a space. This will clear out all white space characters from stdin before reading data.

#include <stdio.h>

int main (void)
{
  char choice;

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

  return 0;
}

Upvotes: 3

Vikdor
Vikdor

Reputation: 24124

You should read out the newline character after that scanf() call. Otherwise, that gets into choice the next time around and so the while loop comes out.

#include<stdio.h>

int main()
{
    char choice;

    do
    {
        printf("Press y to continue the loop : ");
        choice = getchar(); 
        getchar();
    }
    while(choice=='y');
    return 0;
}

Upvotes: 3

Related Questions