Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
366 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

So the first iteration takes the y, but the next iteration doesn't need any input from you because the 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';

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...