fgets不将提供的输入存储在目标变量

时间:2016-08-22 15:12:29

标签: c 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)

这些是我在代码块中从编译器获得的警告:

||=== 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并且没有提示任何输入。 总是将if语句视为true。 并始终对name使用(null)。

您能否告诉我我的代码有什么问题? 我曾被告知使用fgets代替scanfgets。 值得一提的是scanf也给了我类似的问题。

1 个答案:

答案 0 :(得分:2)

在您的代码中,nameagegendermale都是char个变量,而不是char数组。您需要一个阵列才能实现您的定位目标。您的数组必须与传递给fgets()的数组大小相同。

那就是说,

  • atoi()不会将提供的字符串本身转换为int,它会返回转换后的值。您必须将其存储在变量中。
  • male变量,而不是字符串文字,因此变量名称不能用作进行比较。您可以定义包含字符串文字的变量const char * match = "male";,也可以直接使用字符串文字本身("male")进行比较。
  • 无论如何,您需要使用strcmp()来比较字符串。