我正在研究教科书上的一个挑战问题,我应该生成一个 1-10 之间的随机数,让用户猜测,并使用 isdigit() 验证他们的响应。我(大部分)让程序与下面的代码一起工作。
我遇到的主要问题是,使用 isdigit() 需要将输入存储为字符,然后我必须在比较之前对其进行转换,以便比较实际的数字,而不是数字的 ASCII 代码。
所以我的问题是,由于此转换仅适用于数字 0 - 9,我如何更改代码以允许用户在生成的数字为 10 时成功猜出 10?或者,如果我希望游戏的范围为 1-100,那么我该如何实现呢?如果我使用大于 0-9 的可能范围,我可以不使用 isdigit() 验证输入吗?验证用户输入的更好方法是什么?
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <time.h>
int main(void) {
char buffer[10];
char cGuess;
char iNum;
srand(time(NULL));
iNum = (rand() % 10) + 1;
printf("%d\n", iNum);
printf("Please enter your guess: ");
fgets(buffer, sizeof(buffer), stdin);
sscanf(buffer, "%c", &cGuess);
if (isdigit(cGuess))
{
cGuess = cGuess - '0';
if (cGuess == iNum)
printf("You guessed correctly!");
else
{
if (cGuess > 0 && cGuess < 11)
printf("You guessed wrong.");
else
printf("You did not enter a valid number.");
}
}
else
printf("You did not enter a correct number.");
return(0);
}
您可以使用返回值scanf
来判断读取是否成功。那么,你的程序中有两条路径,读取成功和读取失败:
int guess;
if (scanf("%d", &guess) == 1)
{
/* guess is read */
}
else
{
/* guess is not read */
}
在第一种情况下,您将执行程序逻辑所说的任何操作。在里面else
在这种情况下,你必须弄清楚“问题是什么”,以及“该怎么办”:
int guess;
if (scanf("%d", &guess) == 1)
{
/* guess is read */
}
else
{
if (feof(stdin) || ferror(stdin))
{
fprintf(stderr, "Unexpected end of input or I/O error\n");
return EXIT_FAILURE;
}
/* if not file error, then the input wasn't a number */
/* let's skip the current line. */
while (!feof(stdin) && fgetc(stdin) != '\n');
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)