执行while循环,选择C作为char

在下面给出的代码中,如果我按下’y’一次它会重新开始,但是它不会要求下一个重复(或按’y’)。有人可以帮助为什么这个代码在一个循环后被终止?

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

这将是因为stdin被缓冲了。 所以你可能输入一个y的字符串后跟一个\n (换行符)。

所以第一次迭代采用y ,但是下一次迭代不需要你的任何输入,因为\n在stdin缓冲区中是下一个。 但是你可以通过让scanf消耗尾随空格来轻松解决这个问题。

 scanf("%c ",&choice); 

注意: "%c " c后面的空格

但是,如果输入以y结尾,则程序可能陷入无限循环。 所以你还应该检查scanf的结果。 例如

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

你应该在scanf()调用之后读出换行符。 否则,下一次进入选择,所以while循环出来。

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

在scanf格式字符串的第一个字符处,插入一个空格。 这将在读取数据之前清除stdin中的所有空格字符。

 #include  int main (void) { char choice; do { printf("Press y to continue the loop : "); scanf(" %c",&choice); // note the space }while(choice=='y'); return 0; }