从输入文件中读取数据并将其存储到结构数组中

use*_*941 2 c io struct

我计划读取一个输入文件,该文件的名称和数字由缩进分隔,例如

Ben     4
Mary    12
Anna    20
Gary    10
Jane    2
Run Code Online (Sandbox Code Playgroud)

然后再对数据执行堆排序.我无法复制数据并将其存储到结构数组中.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define maxcustomers 100

struct customer{
    char name[20];
    int service;
};

int main()
{
    struct customer list[maxcustomers];
    int i;
    char c;

    FILE *input;
    FILE *output;
    input = fopen("input-file.txt","r");
    output = fopen("output-file.txt","w");

    if(input == NULL){
        printf("Error reading file\n");
        exit(0);
    }
    else{
        printf("file loaded.");

    }
    while((c=fgetc(input))!=EOF){
           fscanf(input, "%s %d", &list[i].name,&list[i].service);

           printf("%s %d", list[i].name,list[i].service);
           i++;
    }
    fclose(input);
    //heapsort(a,n);
    //print to output.txt
    fclose(output);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

到目前为止它注册它打开一个文件并打印"文件已加载"但后来失败.我显然没有将数据保存到结构中.

Dav*_*eri 5

您正在使用两者来使用/遍历文件,fgetc并且fscanf仅使用fscanf:

while (fscanf(input, "%19s %d", list[i].name, &list[i].service) == 2) {
       printf("%s %d", list[i].name, list[i].service);
       i++;
}
Run Code Online (Sandbox Code Playgroud)

请注意,您不需要operator in的地址,&list[i].name因为它已经(衰减到)指针.

  • @tanner,欢迎你,不要忘记在@hellazari的答案中初步确定`i` (2认同)