【问题标题】:reading data from an input file and storing it into a struct array从输入文件中读取数据并将其存储到结构数组中
【发布时间】:2017-06-25 10:40:34
【问题描述】:

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

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

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

【问题讨论】:

  • @chrisaycock "你需要"%s\t%d" 而不是"%s %d" --> 没有。'\t'' ' 都匹配任何空格并且 都不匹配这里需要 %d 占用前导空白。

标签: c struct io


【解决方案1】:

您正在使用fgetcfscanf 使用/遍历文件,仅使用fscanf

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

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

【讨论】:

  • 编译时我得到一个警告:指针和整数之间的比较处理 == 2
  • @tanner,很奇怪,因为 fscanf 返回一个 int 而不是指针
  • 我没有关闭 fscanfs 括号,它现在可以工作了,谢谢。
  • @tanner,不客气,不要忘记初始化i,正如@hellazari 的回答中所指出的那样
【解决方案2】:

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

尝试: int i=0

【讨论】:

    猜你喜欢
    • 2015-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-08
    • 1970-01-01
    • 2019-07-03
    • 1970-01-01
    • 2020-12-26
    相关资源
    最近更新 更多