我想製作一個程序,其中計算機必須猜測用戶(我)挑選的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;
}
爲什麼你不只是用一個字符而已? –