gpt4 book ai didi

c - 循环中的 scanf()

转载 作者:太空宇宙 更新时间:2023-11-04 01:12:34 28 4
gpt4 key购买 nike

我正在尝试制作一个程序,其中计算机必须猜测用户(我)选择的 0 到 100 之间的数字。该程序应该在 7 次尝试中猜出它所做的数字,但我在使用 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;
}

最佳答案

你的 response 缓冲区不是空终止的,这几乎让它在

if (strlen(response) > 1) {

让它成为response[2]

或者,您可以在 scanf 中使用 %c 而不是 %1s

编辑:

尝试在每次 scanf 后调用此函数,它刷新输入缓冲区直到下一个换行符,删除第一个字符后的任何无效输入。

void flush_input()
{
int c = 0;

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

关于c - 循环中的 scanf(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8975793/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com