사용자가 선택한 컴퓨터를 0에서 100 사이의 숫자로 추측해야하는 프로그램을 만들려고합니다. 프로그램은 7 회 시도에서 숫자를 추측해야하지만 scanf()에 문제가 있습니다. 프로그램이 숫자를 추측하려고 할 때, 사용자는 추측 된 숫자가 너무 높거나, 너무 낮거나, 정확하면이를 알려야합니다. 이 프로그램은 사용자가 한 문자 응답을 입력 할 때 제대로 작동하지만 "응답"에 두 개 이상의 문자가있는 경우 이상하게 작동합니다. 그래서 응답을 단 한 문자로 제한하고 싶습니다. 어떻게해야합니까? 거의루프 내 scanf()
if (strlen(response) > 1) {
이 response[2]
확인에이 폭발하게
감사
#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;
}
왜 그냥 대신 하나의 숯불을 사용하지 않는거야? –