c - 第二次 fgets 后出现段错误

标签 c segmentation-fault scanf fgets

我是 C 的新手,我正在研究一个简单的结构练习题。我的代码要求输入名为“员工信息”的输入,询问他们的姓名(一个字符串)、他们被雇用的日期(一个字符串)以及薪水是多少(一个整数)。

第一个 fgets 工作正常,并像往常一样在缓冲区中插入一个换行符。第二个然后接受输入并迅速跳出程序。

我试过在许多不同的地方添加额外的 scanf() 和 getchar() 来去除换行符,但似乎没有任何帮助。

我什至用调试器尝试了所有这些,我唯一得到的是一个段错误,我不太明白。

我环顾四周,询问了人们,似乎没有什么可以解决这个问题。我非常了解与这个问题类似的所有问题,但由于某种原因我无法让它发挥作用。

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

/*****
Initialize a structure to read in and record the employee name, the hire 
date and their salary
******/

//Define structure
struct employee
{
    char *name;
    char *hireDate;
    float salary;
};

int main()
{
    //First hardcode an employee
    struct employee emp1;
    emp1.name = "Karl";
    emp1.hireDate = "May 10, 2019";
    emp1.salary = 60000.00f;

//Now print off this employee
    printf("The first employee's name is %s, he was hired on %s and will make %f per year\n", emp1.name, emp1.hireDate, emp1.salary);

    printf("The next employee is you! Please enter the following information\n");
//Now ask user for second employee
    struct employee emp2;
    printf("Please enter your name: \n");
    fgets(emp2.name, 30, stdin);

//This one works just fine, it produces name\n

    printf("Please enter the date you were hired in regular format (i.e. May 10, 2019)\n");

//I had hoped this scanf() would absorb the above newline
    scanf(" ");

//This takes input, and then jumps out of the program
    fgets(emp2.hireDate, 30, stdin);

    printf("Please enter your salary: \n");
    scanf(" ");
    scanf(" %f",&emp2.salary);

//Now print off this stuff that was typed in
    printf("The first employee's name is %s, he was hired on %s and will make %f per year\n", emp2.name, emp2.hireDate, emp2.salary);
    return 0;
}

最佳答案

你不应该这样声明那些指针,除非你在某个时候为它们malloc() 内存。由于您将输入静态限制为 30 个字符,因此您应该将结构内的字符串声明为数组:char name[31]char hireDate[31]。您的数组中需要额外的 char 来保存终止字符串的 '\0'

请记住,fgets() 将缓冲区大小作为第二个参数,而不是要读取的字符数。要允许用户输入最多 30 个字符,您需要将 31 作为第二个参数传递给 fgets()

关于c - 第二次 fgets 后出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56093898/

相关文章:

在 C 中将项目强制转换到链表末尾

c - if 语句段错误

c - 在c中通过引用传递数组

c - 如何让 sscanf 在 C 中\r\n\r\n 之后开始扫描?

在 C 中创建位图 - 如何将/r/n 写为 1 个字节?

C - struct 中的 bool 数据类型导致异常

c - glibc double free or corruption (out) 不使用 malloc

C scanf() 返回 -1

c - WAV文件分析C(libsndfile,fftw3)

使用gdb调试器出现c代码段错误 "SIGSEGV"