简体   繁体   中英

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

}

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

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 . eg

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM