Я довольно новичок в 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;
}