【问题标题】:I want to scan through a txt file and save those numbers in an array我想扫描一个 txt 文件并将这些数字保存在一个数组中
【发布时间】:2018-05-31 05:43:05
【问题描述】:

这是我编写的程序的一小部分,用于将文件 BesselFunction.txt 的内容保存到数组 ZeroBesselFuncTM 中

constant=fopen("BesselFunction.txt","r");

for(i=0;i<20;i++){
    fscanf(constant,"%lf\n", &zero);
    ZeroBesselFuncTM[i]=zero;
    printf("inside for loop\n");
}

for(i=0;i<20;i++){
    printf("%0.4lf\n", ZeroBesselFuncTM[i]);
}

尽管数组循环了 19 次,但它并没有读取我的输入文件。

【问题讨论】:

  • 检查被调用函数的返回值,fscanf应该返回扫描的元素个数(应该是1,但是如果解析文件内容有错误可能会有所不同)。
  • '\n' 中的fscanf 不是必需的

标签: c arrays scanf


【解决方案1】:

您需要检查文件是否已打开以及是否已读取输入。如果文件过早结束,您还需要停止读取。

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void)
{
    const char *filename = "BesselFunction.txt";
    double ZeroBesselFuncTM[20];
    double zero;
    int i, j, n;
    FILE *constant;

    constant = fopen(filename, "r");
    if (constant != NULL) {
        i = -1;
        do {
            i++;
            n = fscanf(constant, "%lf\n", &zero);
            if (n == 1) {
                ZeroBesselFuncTM[i] = zero;
            } else if (n == 0) {
                fprintf(stderr, "Invalid input\n");
                exit(EXIT_FAILURE);         
            }
        } while ((i < 20) && (n != EOF));
        for(j = 0; j < i; j++) {
            printf("%0.4f\n", ZeroBesselFuncTM[j]);
        }
    } else {
        fprintf(stderr, "Cannot open file %s: %s\n", filename, strerror(errno));
        exit(EXIT_FAILURE);
    }
    return 0;
}

【讨论】:

    【解决方案2】:

    首先检查文件是否正确打开的错误。

    constant=fopen("BesselFunction.txt","r");
    if(constant == NULL) {
      //Process the error
    }
    

    还要检查文件BesselFunction.txt 存在于可执行文件运行的同一目录中。

    第二查看fscanf错误代码以获取更多更新。

    int result = fscanf(constant,"%lf\n", &zero);
    
     if (result <= 0) {
     //Process the error.
     }
    

    【讨论】:

    • result 应该是 &lt;1 如果有错误(很可能是 0 )。
    • 测试result!=1应该足够了
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-12
    • 1970-01-01
    • 1970-01-01
    • 2017-03-30
    • 2022-10-10
    • 1970-01-01
    • 2022-01-13
    相关资源
    最近更新 更多