簡體   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