我正在编写一个程序来存储输入文件中的信息并打印出用户选择的信息。我还没有到达使用选择部分,但我立即遇到了段错误。我知道这意味着我正在尝试访问内存中不存在或无法访问的位置。
我不确定我做错了什么。我正在尝试将输入文件中的信息存储到我的结构中。
输入文件采用这种格式
3
5 Name Name 10 56789
7 Name Name 7 67894
8 Name Name 10 89375
我尝试直接访问结构作为 emp[1].id 等而不是 emp[i].id 等。这也行不通。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
// structures
struct emp
{
int id;
char firstname[10];
char lastname[10];
int department;
float salary;
} emp[10];
// function prototypes
// nothing here yet
int main(int argc, char *argv[])
{
int i = 0;
int choice;
if(argc != 2){
printf("Usage: %s input.txt\n", argv[0]);
exit(EXIT_FAILURE);
}
FILE* inputFile;
inputFile = fopen("input.txt", "r");
if(inputFile == NULL){
printf("Error opening %s\n", argv[1]);
exit(EXIT_FAILURE);
}
// file is open now
// loop to save information from file into structure
int num;
fscanf(inputFile, "%d", &num);
for(i = 0; i < num; i++){
fscanf(inputFile, "%d", emp[i].id);
fscanf(inputFile, "%s", emp[i].firstname);
fscanf(inputFile, "%s", emp[i].lastname);
fscanf(inputFile, "%d", emp[i].department);
fscanf(inputFile, "%f", emp[i].salary);
}
printf("\n");
printf("Welcome to the Employee Database!\n");
printf("---------------------------------\n");
printf("Choose an option:\n");
printf("1: Print empid\n");
printf("2: Print ALL employees\n");
printf("3: Show ALL employees in department\n");
printf("-1: QUIT\n");
scanf("%d", &choice);
// I have not set up the functions to perform the selection options yet
return 0;
}
这是我收到的输出。
c803@cs2:~A5$ gcc A5.c
c803@cs2:~A5$ ./a.out input.txt
Segmentation fault
最佳答案
这里 fscanf 获取变量的内存地址来存储读取的数据,就像 scanf() 一样。 您需要将“&”放在 emp[i].id 和除字符数组之外的所有其他数据成员前面,因为数组名称本身给出了数组的第一个数组成员的地址。 所以代码应该是::
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
// structures
struct emp
{
int id;
char firstname[10];
char lastname[10];
int department;
float salary;
} emp[10];
// function prototypes
// nothing here yet
int main(int argc, char *argv[])
{
int i = 0;
int choice;
if(argc != 2){
printf("Usage: %s input.txt\n", argv[0]);
exit(EXIT_FAILURE);
}
FILE* inputFile;
inputFile = fopen("input.txt", "r");
if(inputFile == NULL){
printf("Error opening %s\n", argv[1]);
exit(EXIT_FAILURE);
}
// file is open now
// loop to save information from file into structure
int num;
fscanf(inputFile, "%d", &num);
for(i = 0; i < num; i++){
fscanf(inputFile, "%d", &emp[i].id);
fscanf(inputFile, "%s", emp[i].firstname);
fscanf(inputFile, "%s", emp[i].lastname);
fscanf(inputFile, "%d", &emp[i].department);
fscanf(inputFile, "%f", &emp[i].salary);
}
printf("\n");
printf("Welcome to the Employee Database!\n");
printf("---------------------------------\n");
printf("Choose an option:\n");
printf("1: Print empid\n");
printf("2: Print ALL employees\n");
printf("3: Show ALL employees in department\n");
printf("-1: QUIT\n");
scanf("%d", &choice);
// I have not set up the functions to perform the selection options yet
return 0;
}
关于c - 将文件中的信息存储到 C 中的结构中 - 遇到段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56620872/