2016-08-22 33 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