2016-08-22 100 views
-4

當我運行這段代碼:與fgets不存儲所提供的輸入在目標變量

#include<stdio.h> 
#include<stdlib.h> 

int main() 
{ 
    char name , age , gender , male; 

    printf("Please enter your name \n"); 

    fgets(name, 20 ,stdin); 

    printf("Please enter your age \n"); 

    fgets(age , 2 , stdin); 

    printf("Please enter your gender \n"); 

    fgets(gender , 7 , stdin); 

    atoi(age); 

    { 
     if (age < 50 && gender == male) 

      printf(" You're fit to play\n Welcome player ,%s \n",name); 

      else printf("Sorry , %s. You're not fit to play", name); 

    } 
    return 0; 
} 

我得到這樣的輸出:

please enter your name 
please enter your age 
please enter your gender 
you're fit to play 
welcome player, (null) 

而且這些都是警告我從編譯器得到我的codeblocks:

||=== Build: Release in justexploring1 (compiler: GNU GCC Compiler) ===| 
D:\Project\C language\justexploring1\main.c||In function `main':| 
D:\Project\C language\justexploring1\main.c|8|warning: passing arg 1 of `fgets' makes pointer from integer without a cast| 
D:\Project\C language\justexploring1\main.c|10|warning: passing arg 1 of `fgets' makes pointer from integer without a cast| 
D:\Project\C language\justexploring1\main.c|12|warning: passing arg 1 of `fgets' makes pointer from integer without a cast| 
D:\Project\C language\justexploring1\main.c|13|warning: passing arg 1 of `atoi' makes pointer from integer without a cast| 
D:\Project\C language\justexploring1\main.c|16|warning: format argument is not a pointer (arg 2)| 
D:\Project\C language\justexploring1\main.c|17|warning: format argument is not a pointer (arg 2)| 
D:\Project\C language\justexploring1\main.c|6|warning: 'name' might be used uninitialized in this function| 
D:\Project\C language\justexploring1\main.c|6|warning: 'age' might be used uninitialized in this function| 
D:\Project\C language\justexploring1\main.c|6|warning: 'gender' might be used uninitialized in this function| 
D:\Project\C language\justexploring1\main.c|6|warning: 'male' might be used uninitialized in this function| 
||=== Build finished: 0 error(s), 10 warning(s) (0 minute(s), 0 second(s)) ===| 

它完全忽略了fgets,並沒有提示任何輸入。 總是對待如果陳述是真實的。 並始終使用(空)name

你能告訴我我的代碼有什麼問題嗎? 我曾被告知使用fgets而不是scanfgets。 值得一提的是scanf也給了我類似的問題。

+4

幫你一個忙:**打開所有的編譯器警告並留意它們**。 – pmg

+0

我剛剛給這個問題加了編譯警告。其中有很多。 –

+0

strcmp?我不知道這個功能。你能告訴我它是如何使用的嗎? –

回答

2

在你的代碼,nameagegendermale都是char變量,而不是char陣列。你將需要一個數組來實現你的目標。您的陣列的大小必須與您傳遞給fgets()的大小相同。

這就是說,

  • atoi()不提供的字符串本身轉換爲int,它返回轉換的結果。你必須把它存儲在一個變量中。
  • male可變,而不是一個字符串文字,所以變量名不能被用作用於比較的。您可以定義一個包含字符串文字const char * match = "male";的變量,或直接使用字符串文字本身("male")進行比較。
  • 無論如何,您需要使用strcmp()來比較字符串。
+0

那麼如何將該值轉換爲整數?或者我如何提示輸入一個整數? –

+0

@AllanMayers如果需要,您可以將'atoi()'的返回值存儲到'int'變量中。 –

+0

@AllanMayers這是一個適用於你的[demo](http://ideone.com/RKL2VT)。我不認爲歧視性別是正確的,但是對於不喜歡煎餅的人......絕對是:-)(如果你不明白我的意思,請看看演示)!不過,它應該很容易改回。我希望能幫到你! – iRove