2013-03-18 62 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'); 
}