I'm pretty new to C and I'm working on a simple practice problem with structures. My code asks for input termed "employee information", asking for their name (a string), the date they were hired (a string) and what the salary will be (an integer).
The first fgets works fine, and sticks a newline in the buffer as usual. The second then takes input and promptly jumps out the program.
I've tried sticking extra scanf()'s and getchar()'s in lots of different places to get rid of the newline, but nothing seems to help.
I even tried all of this with the debugger, and the only thing I get is a segmentation fault, which I don't really understand.
I have looked around, asked people and nothing seems to solve this problem. I am more than aware of all the questions similar to this one, but for some reason I just can't get it to work.
#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;
}
fgets(emp2.name, 30, stdin);
.emp2.name
is uninitialized; reading from an uninitialized variable is an error. – melpomene