首页 > 解决方案 > 如何在C中读取每行带有数字的文件?

问题描述

我正在尝试读取一个包含 10 个数字的文件,然后将它们添加到一个数组中,以便稍后对它们进行排序,但我无法读取它们。不知道为什么这对我不起作用,有人可以解释一下吗是错的?每行只有一个数字。

10.05
11.01
9.03
    double nums[10] = {0};
    int count;

    if ((fptr = fopen("filename", "r")) == NULL){
            printf("Error opening file.\n");
    }

    while ((c = getc(fptr)) != EOF){
            if (c != '\n'){
                    nums[count] = (double)c;
                    count = count + 1;
            }
    }
    fclose(fptr);

标签: c

解决方案


怎么了:

  • 您只存储一个字符。
  • count每次都在非换行符上更新,而更新应该在换行符上。
  • count未经初始化就使用。
  • 转换double为不适合这种用法。

可能的修复:

int c;
FILE* fptr;

char line[1024]; // add line buffer and size tracking
int lineCount = 0;
double nums[10] = {0};
int count = 0; // initialize count

if ((fptr = fopen("filename", "r")) == NULL){
        printf("Error opening file.\n");
} else { // avoid using NULL to read file

    while ((c = getc(fptr)) != EOF){
            if (c == '\n'){ // update nums on newline character
                    line[lineCount] = '\0'; // don't forget to terminate the string
                    nums[count] = atof(line); // atof() from stdlib.h is useful to convert string to number
                    count = count + 1;
                    lineCount = 0; // start to read next line
            } else { // read line contents
                line[lineCount] = (char)c;
                lineCount = lineCount + 1;
            }
    }
    fclose(fptr);
}

推荐阅读