2020年1月14日 星期二

用scanf或getchar()讀取 y/n值 所遇問題

之前無聊想寫一個猜數字的遊戲,結果在問到要不要繼續時,每次輸入y,接下來都會印出兩次結果。

譬如說下面的code:
#include <stdio.h>

int main()
{
 char c;
 while (1)
 {
  printf("do you what to continue? ");
  scanf_s("%c", &c);
  if (c == 'n')
   break;
 }
 return 0;
}

就會出現:
輸入一個y,結果印了兩次"do you want to continue?"

後來查了一下網路,好像是因為scanf用%c讀值的時候,一次只接一個字元,但使用者是輸入了y或n被存到c之後,又再輸入了\n。第一個輸入的y/n的確被拿去判斷了沒錯,所以才會有前一個"do you want to continue? ",但後一個換行符號則被存到緩衝區,等下一次再拿出來判斷,造成多輸出了一次。

所以如果在scanf後多加一行,變成:
#include <stdio.h>

int main()
{
 char c;
 while (1)
 {
  printf("do you what to continue? ");
  scanf_s("%c", &c);
  getchar();
  if (c == 'n')
   break;
 }
 return 0;
}

也就是用getchar()把\n吃掉,就沒有問題了。



這個問題我一開始不知道怎麼下關鍵字,只好先跳過,是之後看到課本上有一行:
while(getchar()!='\n');
我才慢慢找對方向。
相關關鍵字大概是:clean input buffer, while loop error, getchar() in while loop 等等?

參考文章:
How to clear input buffer in C?
http://c-faq.com/stdio/scanfc.html

也可以參考http://squall.cs.ntou.edu.tw/cprog/practices/scanfCommonTraps.pdf

沒有留言:

張貼留言