user2137944
user2137944

Reputation: 73

Reading a data file - unwanted extra value at the end of array

I'm fairly new to programming so apologies for any silly errors/oversights.
I'm trying to write a program that reads a data file with 3 columns of numbers and puts them into arrays. I'd like to be handle files of up to, say 100 elements.
The issue is that after I read a data file which I know to contain 20 elements, an extra value or 0.00000 is slapped onto the end of each array, so it has written 21 values instead of the 20 I want.

My code looks like this:

#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++;
}

So when I print out the arrays I get the 20 values I want PLUS an unwated 0.000000 value at the end of each. This created a lot of problems later when I try and plot some of the data.

From the searching I've done here and elsewhere it looks like it is the while(!feof(f)... loop that's the problem.

I'd be really grateful if anyone can help me get arrays just containing the values in the .dat file.

Thanks

Upvotes: 2

Views: 253

Answers (2)

qPCR4vir
qPCR4vir

Reputation: 3571

The array index beggin in 0 like in volume[0], that is, you initialize cnt=0; not 1. Additionaly,

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

This break will probably solve the problem.

EDIT:

The code i can use to print:

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++; ....

Is here allready corrected? Is not, you print one more from 0 to cnt-1, and enter from 1 to cnt-1. Only why at ende and not at begging of the array have you the 0? Anyway, cold you test initializing cnt to 0? Is this exactly what do you use?

Upvotes: 1

Josh Wonser
Josh Wonser

Reputation: 41

Check out how you are printing out the array. Your indices might be off leading to a trailing 0.0 value. Also you should initialize cnt=0.

Upvotes: 0

Related Questions