0

Hi,

Im reading a file, with 2 columns. this is working
such as

1999	5848946
2000	5458445
2001	5757585
2002	7699865
2003	7459758
2004	5797054

as Im reading I want to be able to count how many rows I've read and also add the all values as im reading from the second column, could some help plz
This is the code

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

struct data{

	int x;
	int y;
};
void read_info(void);

int main()
{
	read_info();
}

void read_info(void)
{
	FILE *stocks;
	struct data stock;
	int x;
	char buf[80];
	int total = 0;
	int numberofrecords = 0;
	
	stocks = fopen("banana.dat", "r");
	if(stocks==NULL)
	{
		puts("No data in file");
		return;
	}
	
	while (fgets(buf, 80, stocks) != NULL && !feof(stocks)) 

	{
		sscanf(buf, "%d %d", &stock.x, &stock.y); 
		
		printf("n1 = %d n2 = %d\n", stock.x, stock.y); 
		
		/*numberofrecords = stock.x++;
		total += stock.y; 
               printf("%d %d", numberofrecords, total);*/
	}
	
	
	fclose(stocks);
	
}
2
Contributors
2
Replies
3
Views
9 Years
Discussion Span
Last Post by electromania
0

All you need to do is keep a count of rows and a running sum of the values. You pretty much had it:

while (fgets(buf, 80, stocks) != NULL && !feof(stocks)) {
  sscanf(buf, "%d %d", &stock.x, &stock.y); 
  printf("n1 = %d n2 = %d\n", stock.x, stock.y); 
  total += stock.y;
  ++numberofrecords;
}
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.