2013-03-06 32 views
2

我对编程颇为陌生,所以对于任何愚蠢的错误/疏忽表示歉意。
我想写一个程序,读取数据文件的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个值我想加一个unwated 0.000000值,在每个月底。后来当我尝试绘制一些数据时,这就造成了很多问题。

从搜索我在这里所做的和其他地方看起来它是while(!FEOF(F)...循环这就是问题所在。

我会非常感激,如果有人能帮助我得到阵列只是包含在.dat文件中的值。

感谢

回答

1

0的数组索引beggin像​​,那就是,你初始化cnt=0;不是1 Additionaly,

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。只有为什么在进行而不是在乞讨阵列你有0?无论如何,冷你测试初始化​​cnt为0?这正是你使用什么?

+0

感谢您的回复。我试着按照你的建议放入中断,但存在同样的问题 - 仍然在数组中获得这个流氓价值。任何其他方式,我可以尝试写它? – user2137944 2013-03-06 01:22:56

+1

@ user2137944你如何打印? – qPCR4vir 2013-03-06 01:27:21

+0

i = 0; (i user2137944 2013-03-06 01:30:59

0

看看你是如何打印出阵列的。您的指数可能会失去最终的0.0值。你也应该初始化cnt=0