[英]C guessing game using while loops to limit user guesses and isdigit for verification
[英]C number guessing game with isdigit() verification
我正在研究教科書中的一個挑戰性問題,我應該在其中生成1-10之間的隨機數,讓用戶猜測並使用isdigit()驗證其響應。 我(主要是)使程序可以使用下面的代碼。
我遇到的主要問題是,使用isdigit()要求將輸入存儲為char,然后在比較之前我必須將其轉換,以便比較實際數字而不是數字的ASCII代碼。
所以我的問題是,由於此轉換僅適用於數字0-9,我如何更改代碼以允許用戶在生成數字時成功猜出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');
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.