Hello, I try to write a code to calculate the average value from a text file but the dumb thing is I has to count the no. of data manually to initialize the array. (here is 1000).
Here is the code:
Code:
#include <stdio.h>
#include <stdlib.h>
int main(){
FILE *p;
p = fopen("myfile.txt", "r");
int Array[1000];
int i;
double sum=0.0;
for (i = 0; i < 1000; i++)
{
fscanf(p, "%d", &Array[i] );
printf("Number is: %d\t %d\n\n", Array[i],i);
sum = sum + Array[i];
}
printf("The average weight is %lf",sum/1000);
fclose(p);
return 0;
}
It works but i just want it to count the no. of data automatically. So i search something that capable to count the no. :
Code:
#include<stdio.h>
int main(void)
{
FILE *p;
char ch;
int w=0;
p=fopen("myfile.txt","r");
if(p==NULL)
{
printf("file not found");
}
else
{
ch=fgetc(p);
while(ch!=EOF)
{
printf("%c",ch);
if(ch==' '||ch=='\n')
{
w++;
}
ch=fgetc(p);
}
printf("\nWords in a file are=%d",w);
}
fclose(p);
getch();
return 0;
}
How do I combine the two and make use of the 'w' in the first program? I've tried but fail. Hope someone can guide me.