2013-03-18 59 views
0

我正在从我的教科书中挑战问题,我应该在1-10之间生成一个随机数,让用户猜测,并使用isdigit验证其响应)。我(主要)让程序使用下面的代码。用isdigit()验证的C号猜谜游戏

我遇到的主要问题是使用isdigit()要求输入存储为字符,然后我必须在比较之前进行转换,以便比较实际的数字,而不是数字的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); 
} 
+1

可以使用输入一个ENTER?输入一个数字?用户可以输入'$'吗? '$'是数字吗?验证输入的*字符串*(可能用每个字符的'isdigit()')后,将*字符串*转换为数字('int',可能带有'strtol()')并从那里开始。 – pmg 2013-03-18 11:05:16

回答

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'); 
}