繁体   English   中英

在C中以char的形式执行while循环

[英]Do while loop with choice as char in C

在下面给出的代码中,如果我再按一次``y''将再次出现,但它不是在要求下一个重复的书(或按``y'')。有人可以帮忙为什么此代码在一个循环后终止吗?

 main()
{
 char choice;

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

}

您应该在该scanf()调用之后读出换行符。 否则,下次会选择这​​种方式,因此while循环就会出现。

#include<stdio.h>

int main()
{
    char choice;

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

那是因为stdin被缓冲了。 因此,您可能输入的是y字符串,后跟\\n (换行符)。

因此,第一个迭代使用y ,但是下一个迭代不需要您的任何输入,因为\\n在stdin缓冲区中是下一个。 但是,您可以通过使scanf占用尾随空白来轻松解决此问题。

scanf("%c ",&choice);

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

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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