writes:
> the code is workin well for the firs five iterations...but thn it isnt
> doing the computations properly after the 5th iteration (sumthing is
> goin wrong in the if loop)
On my system it works with the data you posted elsewhere (as far as I
can tell). What is it that goes wrong?
> #include<stdio.h>
> #include<stdlib.h>
> #include<string.h>
>
> int main()
> {
> FILE *fp;
> char ch,str[100],str1[100];
>
> int c=0,i,j;
> float t=0.0,t1=1.0472789115646258,t2=0.0,sum=0.0,avg=0.0 ,check=0.0;
>
> fp=fopen("pt1.txt","rb");
> if (fp==NULL)
> perror ("Error opening file: pt1.txt");
> else
> {
> while(!feof(fp))
Not usual the wight way to do input in C. See the FAQ at
http://c-faq.com/ (specifically Q 12.2).
> {
>
> fscanf (fp, "%s", str);
> i=strcmp(str,"time");
> if(i==0)
> {
> printf("t1=%f\n",t1);
> fscanf (fp, "%s", str);
> fscanf (fp, "%f",&t);
>
>
> fscanf (fp, "%s", str);
> j=strcmp(str,"value");
>
>
> if(j==0)
> {
> fscanf (fp, "%s", str);
> fscanf (fp, "%f",&t2);
> printf("t2=%f\n",t2);
> }
>
> check=t1+0.1;
This is very convoluted. fscanf can tell you if the input looks right
(i.e. has the right fixed strings in it) and can tell you that the
numbers were read and converted correctly. For example:
do {
switch (fscanf(fp, "time = %f value = %f", &t, &v)) {
case 2:
printf("%f %f\n", t, v); /* change this to do what you want */
break;
case 1:
printf("Time not followed by value.\n");
break;
default:
fgetc(fp);
}
} while (!feof(fp));
It relies on allowing fscanf to fail a lot, but unless you need
blistering speed, that won't be a problem.
--
Ben.