You are here:

C/Input files

Advertisement


Question
Hi again Tony, I wrote a program that does some calculations on the input from an input files. The program works fine, except I noticed that it feeds in the very last value twice, regardless of how many values are in the file. Any idea why?

Here's the code:
#include <stdio.h>
#include <math.h>

int main()
{
  float x = 0;
  float sum = 0;
  float sumdiffxsquared = 0;
  float average = 0;
  float stddev = 0;
  int count = 0;

  while(!feof(stdin)) {
    printf("Enter a number:\n");
    scanf("%f", &x);
    printf("%2.2f\n",x);
    count++;
    sum = sum + x;
    average = sum / count;
    sumdiffxsquared = sumdiffxsquared + pow(x-average,2);
  }

  stddev = pow(sumdiffxsquared/count,.5);
  printf("Sum: %2.2f\n",sum);
  printf("Average: %2.2f\n",average);
  printf("Standard Deviation: %2.2f\n",stddev);
}

Thanks!

Answer
Hi David,

After the last number is scanned by scanf it does not reach EOF, and therefore feof returns zero. On the last scan, scanf returns EOF and does not set "x" again causing it to hold the previous value a second time. By checking the return value of scanf you can exit the loop.


#include <stdio.h>
#include <math.h>

int main()
{
 float x = 0;
 float sum = 0;
 float sumdiffxsquared = 0;
 float average = 0;
 float stddev = 0;
 int count = 0;

 while(!feof(stdin)) {
   printf("Enter a number:\n");
   if(EOF == scanf("%f", &x))
       break;
   printf("%2.2f\n",x);
   count++;
   sum = sum + x;
   average = sum / count;
   sumdiffxsquared = sumdiffxsquared + pow(x-average,2);
 }

 stddev = pow(sumdiffxsquared/count,.5);
 printf("Sum: %2.2f\n",sum);
 printf("Average: %2.2f\n",average);
 printf("Standard Deviation: %2.2f\n",stddev);
}


output:

$ echo -e "1\n2\n3\n" | ./a.out
Enter a number:
1.00
Enter a number:
2.00
Enter a number:
3.00
Enter a number:
Sum: 6.00
Average: 2.00
...


C

All Answers


Answers by Expert:


Ask Experts

Volunteer


Tony Nazzal

Expertise

I will answer any c language programming and syntax questions.

Experience

I have almost a decade of c programming experience.

Education/Credentials
I have a bachelor of science degree and several years of industry experience.

©2016 About.com. All rights reserved.