gpt4 book ai didi

c - 如何将值传递给结构变量然后将结构写入文件?

转载 作者:行者123 更新时间:2023-12-02 06:38:08 26 4
gpt4 key购买 nike

如何将值传递给结构变量 我试图从用户那里获取员工信息,然后将它们写入文件,但在输入员工姓名后出现了段错误。这是我的代码。

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

struct record_em{
int id;
char name[20];
int salary;
int age;
};

int main( void )
{
struct record_em employee;
FILE *fp;
int id, salary, age;
char name[20];
int n=1;

fp = fopen("empRecord.dat","a");
while(n==1){
printf("\nEnter Employee ID\n");
scanf("%d",&id);
employee.id=id;
printf("\nEnter Employee Name\n");
scanf("%s",name);
employee.name=name;
printf("\nEnter Employee Salary\n");
scanf("%d",&salary);
employee.salary=salary;
printf("\nEnter Employee Age\n");
scanf("%d",&age);
employee.age=age;
fwrite(&employee,sizeof(employee),1,fp);
printf("Enter 1 to add new record \n");
scanf("%d",&n);
}

fclose(fp);

return 0;
}

输出(取自评论):

Fatmahs-MacBook-Air:~ fatmah$ gcc -o em em.cFatmahs-MacBook-Air:~ fatmah$ ./emEnter Employee ID88Enter Employee NameuuSegmentation fault: 11 

最佳答案

改变

scanf("%s",name);
employee.name=name;

scanf("%s",name);
strcpy(employee.name, name);

更好的是,正如 Dukeling 和 hmjd 所建议的那样

scanf("%19s", employee.name);

关于c - 如何将值传递给结构变量然后将结构写入文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13526867/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com