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

时间:2017-02-08 00:24:07

标签: c struct io

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

Ben     4
Mary    12
Anna    20
Gary    10
Jane    2

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

#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;
}

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

2 个答案:

答案 0 :(得分:5)

您正在使用fgetcfscanf使用/浏览文件,仅使用fscanf

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

请注意,&list[i].name中不需要运算符的地址,因为它已经(衰减到)指针。

答案 1 :(得分:3)

除了@Keine Lust所说的, i没有初始值,你不能像你一样使用/增加整数而没有值。

尝试: int i=0

相关问题