2012-01-23 66 views
1

我想製作一個程序,其中計算機必須猜測用戶(我)挑選的0到100之間的數字。程序應該猜測7次嘗試的次數,但是我遇到了scanf()的問題。當程序嘗試猜測數字時,用戶必須告訴它猜測的數字是否太高,太低或正確。當用戶只輸入一個字符響應時,該程序工作正常,但當「響應」中有多個字符時會嚇倒。所以我想限制迴應只有一個字符。我該怎麼做呢?scanf()在循環

感謝

#include <stdio.h> 
#include <string.h> 

int main() { 
    char response[1]; 
    int numOfGuesses = 1; 
    int min = 0; 
    int max = 100; 
    int guess = (max+min)/2; 
    int end = 0; 

    do { 
     printf("%d) %d: (h)igh, (l)ow, or (c)orrect? ", numOfGuesses, guess); 
     if (scanf("%1s", response) == 1) { 

      printf("%s \n", response); 
      if (strlen(response) > 1) { 
       printf("D'oh! Wrong response!! \n"); 
      } else { 
       if (response[0] == 'h') { 
        max = guess; 
        numOfGuesses++; 
       } else if (response[0] == 'l') { 
        min = guess; 
        numOfGuesses++; 
       } else if (response[0] == 'c') { 
        printf("Correct! It took %d turns. \n", numOfGuesses); 
        end = 1; 
       } else { 
        printf("D'oh! Wrong response! \n"); 
       } 

       guess = (max+min)/2; 
      } 

     } else { 
      end = 1; 
     } 

    } while (end == 0); 

    return 0; 
} 
+0

爲什麼你不只是用一個字符而已? –

回答

4

response緩衝區不爲空終止,這幾乎使得它在爆炸

if (strlen(response) > 1) { 

讓它response[2]

或者,您可以使用%c代替%1s代替scanf

編輯:

嘗試調用每一個scanf函數後這個功能,它刷新輸入緩衝區,直到下一個新行,第一個字符後,刪除無效的輸入。

void flush_input() 
{ 
    int c = 0; 

    do 
    { 
     c = getchar(); 
    } while (c != EOF && c != '\n'); 
} 
+0

即使進行了這些更改,我的代碼仍然在循環中變得怪異 – likebeats

+0

怪胎究竟是什麼意思?如果用戶輸入多於一個字符,則可能不得不排空輸入緩衝區,否則剩餘的字符將被下一個scanf讀取。 – pezcode

0

你爲節省內存獲得加分?

#include <stdio.h>向上頂,然後聲明迴應是肥胖型數組:char response[BUFSIZ];

你應該在循環之前初始化它,只是因爲這是一個好習慣:*響應=「\ 0」;

因爲你沒有做太多,你可以調用gets(response)而不是scanf()。這將在輸入的整行中讀取。現代編譯器和/或運行時間會對gets()提出懷疑,因爲它可以從提供的數組的末尾運行(這正是您的scanf()所做的),建議使用fgets()。在更正確的代碼片段變爲:

fgets(response, sizeof response, stdin); 
0

使用

if (scanf("%1s", response) == 1) { 

if (scanf("%2s", response) == 1) { 

代替,這使得讀取多達2個字符,而不是僅僅1編譯器在同一時間