【问题标题】:Reading a data file - unwanted extra value at the end of array读取数据文件 - 数组末尾不需要的额外值
【发布时间】:2013-03-06 00:54:34
【问题描述】:

我对编程还很陌生,因此对任何愚蠢的错误/疏忽深表歉意。
我正在尝试编写一个程序来读取具有 3 列数字的数据文件并将它们放入数组中。我想处理多达 100 个元素的文件。
问题是,在我读取一个我知道包含 20 个元素的数据文件后,一个额外的值或 0.00000 被添加到每个数组的末尾,因此它写入了 21 个值而不是我想要的 20 个。

我的代码如下所示:

#include <stdio.h>
#include <cpgplot.h>
#include <stdlib.h>
#include <math.h>
#define MAXELEMENTS 100


int main()
{
/*Declare variables*/
float volume[MAXELEMENTS], temp[MAXELEMENTS], pressure[MAXELEMENTS];
int cnt = 1;
int i;
FILE *f;
char headings[MAXELEMENTS];
char filename[100];


/*Prompt user for file name*/
printf("Please enter the name of the file: ");
scanf("%s", &filename);

f = fopen(filename, "r");
if(f == NULL)
{
printf("File not found\n");
exit(EXIT_FAILURE);
}

/* Buffer line to read the headings of the data*/
fgets(headings, MAXELEMENTS, f);

/* Read records from the file until the end is reached*/
while(!feof(f) && cnt<MAXELEMENTS){
if (fscanf(f, "%f %f %f\n", &volume[cnt], &temp[cnt], &pressure[cnt]) > 0) cnt++;
}

因此,当我打印出数组时,我得到了我想要的 20 个值,并且在每个数组的末尾加上了一个未经处理的 0.000000 值。当我尝试绘制一些数据时,这会产生很多问题。

从我在这里和其他地方所做的搜索看来,问题在于 while(!feof(f)... 循环。

如果有人可以帮助我获取仅包含 .dat 文件中的值的数组,我将不胜感激。

谢谢

【问题讨论】:

    标签: c arrays scanf


    【解决方案1】:

    数组索引像volume[0]一样从0开始,也就是说,你初始化cnt=0;而不是1。 另外,

    if (fscanf(f, "%f %f %f\n", &volume[cnt], &temp[cnt], &pressure[cnt]) > 0) 
       cnt++; 
    else 
       break; 
    

    这个break 可能会解决问题。

    编辑:

    我可以用来打印的代码:

    i =0; // here you begging actualy with 0 or 1? Is here alrready corrected? 
    while (i < cnt)
    { printf("%f\t %f\t %f\n", volume[i], temp[i], pressure[i]);
      i++; ....
    

    这里已经更正了吗?不是,你从0到cnt-1再打印一个,从1到cnt-1输入。只是为什么在 ende 而不是在乞求数组时你有 0?无论如何,冷你测试初始化​​ cnt 为 0?这正是你用的吗?

    【讨论】:

    • 感谢您的回复。我尝试按照您的建议进行中断,但存在同样的问题 - 仍然在数组中获得这个流氓值。我可以尝试其他任何方式来编写它吗?
    • @user2137944 你如何打印?
    • i =0; while (i
    • 抱歉,这里的格式不太清楚。当我稍后用趋势线绘制一些数据时,这个问题最为明显。它绘制了整个数组(这应该是一件好事),但我的线有这个零值把事情搞砸了
    • @user2137944 见编辑:啊,趋势线 vol vs temp ??
    【解决方案2】:

    查看您是如何打印出数组的。您的索引可能会导致尾随 0.0 值。你也应该初始化cnt=0

    【讨论】:

      猜你喜欢
      • 2023-03-16
      • 1970-01-01
      • 2012-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多