【问题标题】:fgets does not prompt for user input. What is the difference?fgets 不提示用户输入。有什么区别?
【发布时间】:2015-06-26 11:02:29
【问题描述】:

我在下面使用 fgets 有两个场景。两种方案都在同一个文件中,如下所示。

struct sth
{
    char str[10];
    int num; 
};

void getIt(struct sth **M){ 
    char *b;
    (*M)=malloc(sizeof(struct sth));

    printf("give me an integer:");
    fgets(b,1,stdin);  // output must be an address 
    (*M)->num = atoi(b);

    printf("give me a string:");
    fgets((*M)->str,10,stdin);

}


int main(int argc, char const *argv[])
{
    struct sth *myThing;
    getIt(&myThing);
    printf("Heres the string %s\n", myThing->str);
    printf("Heres the num \n", myThing->num);
    return 0;
}

这是输出。请注意,它不会提示用户输入整数,它只是打印“给我一个整数”,然后直接转到下一个打印语句。为什么这样做?

give me an integer:give me a string:sdf
Heres the string sdf

Heres the num

这个小问题是大问题中的大问题,所以这只是大问题的一个缩影。

【问题讨论】:

    标签: c string char stdin fgets


    【解决方案1】:

    你有:

    fgets(b,1,stdin);  // output must be an address 
    

    但是,b 必须是有效地址,才能保存您要读取的数据。在您的代码中,b 被定义为一个指针,但它不指向任何有效地址。

    类似的东西:

    char b[20]; // Make it large enough to hold the data
    

    是必须的。

    我不确定您为什么使用fgets 读取数据并使用atoi 将其转换为数字。另一种选择是使用fscanf

    【讨论】:

    • fscanf 读取无限数量的字符,这对我正在尝试做的事情来说很危险。所以,我选择了 fgets。请记住,此示例是更大操作的一部分。
    【解决方案2】:
    1. 您还没有为b 分配空间,fgets() 期望它的第一个参数指向足够的内存来存储结果,也就是您作为第二个参数传递给它的大小。

    2. 由于大小参数为1fgets() 正在读取一个空字符串,您需要它至少为3,因为fgets() 需要空间用于'\n' 和终止nul

      所以试试这个

      char b[3];
      
      fgets(b, sizeof(b), stdin);
      *M->num = atoi(b);
      
    3. 在尝试对指针执行任何操作之前,您必须检查 malloc() 是否返回 NULL

    【讨论】:

      猜你喜欢
      • 2021-11-29
      • 2011-02-14
      • 2021-03-02
      • 1970-01-01
      • 2016-05-06
      • 2015-02-20
      • 2017-09-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多