Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
374 views
in Technique[技术] by (71.8m points)

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

}
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...