简体   繁体   English

fscanf 在读取文件时重复数字

[英]fscanf is duplicating numbers while reading from a file

I am trying to read numbers from a file and put them into a 2d array, but the first number of each line is being put into the place of the last number of the previous line.我正在尝试从文件中读取数字并将它们放入二维数组中,但是每行的第一个数字被放入前一行的最后一个数字的位置。

output should look like this: output 应如下所示:

11  14  12  07  1   8.7
11  14  11  58  143 8.6
11  14  13  03  163 8.9
11  13  18  06  1   7.3

but instead comes out like this:但结果是这样的:

11  14  12  07  1   11
11  14  11  58  143 11
11  14  13  03  163 11
11  13  18  06  1   7.3

This is the loop that is putting the values into the array:这是将值放入数组的循环:

    double all_data[entry_counter-1][5];
    int col_counter = 0;
    int row_counter = 0;

    for(int i=0; i<=entry_counter/6-1; i++) {
        col_counter = 0;
        for (int j = 0; j <= 5; j++) {
            fscanf(input_file, "%lf\n", &v);

            all_data[row_counter][col_counter] = v;
            col_counter++;
        }
        row_counter++;
    }

Your code is overly complicated and wrong.您的代码过于复杂和错误。

This should do the job:这应该做的工作:

int cols = 6;
int rows = entry_counter / cols;
double all_data[rows][cols];

for(int row_counter = 0; row_counter < rows; row_counter++) {
    for (int col_counter = 0; col_counter < cols; col_counter++) {
        fscanf(input_file, "%lf\n", &all_data[row_counter][col_counter]);
    }
}

Keep it simple.把事情简单化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM