第二个fget之后的分割错误

时间:2019-05-11 20:09:40

标签: c segmentation-fault scanf fgets

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

第一个fget正常工作,并照常在缓冲区中插入换行符。然后第二个输入并立即跳出程序。

我尝试在许多不同的地方粘贴多余的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;
}

2 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:1)

您没有分配内存来存储gets读取的值。

emp2中,指针未初始化,对fgets的第一次调用也可能发生段错误。

例如,您需要使用malloc或将字符串字段定义为char name[30]来分配存储值的内存。