- #1
sh4rif
- 4
- 0
Hello to all
I have been given a task in "C" environment ... to read a text file with a sequence of positive integers the sequence should be terminated with a sentinel value of -1
Values in text file is : 6 9 17 4 12 8 7 -1
We have to read the integers from text file, display the integers, total, average. the value -1is a sentinel value and is not part of the sequence.
I’ve created a code this works fine but I want a better code then this I hard quoted -1 could anyone please help me to improve my code please.
thanks once again
Usman
below is my code
I have been given a task in "C" environment ... to read a text file with a sequence of positive integers the sequence should be terminated with a sentinel value of -1
Values in text file is : 6 9 17 4 12 8 7 -1
We have to read the integers from text file, display the integers, total, average. the value -1is a sentinel value and is not part of the sequence.
I’ve created a code this works fine but I want a better code then this I hard quoted -1 could anyone please help me to improve my code please.
thanks once again
Usman
below is my code
Code:
#include <stdio.h>
char filename[] = "C:\\numbers.txt";
int numbers, total, num;
float average;
FILE *fp;
main()
{
if((fp = fopen(filename, "r")) == NULL)
printf("\n\n\t\t\tError opening file.");
else
{
printf("\n\n\t\t");
while(numbers>=0){
fscanf(fp, "%d", &numbers);
if(numbers != -1)
{
printf("%4d", numbers);
total = total + numbers;
num++;
}
}
average = (float) total/num;
printf("\n\n\t\tTotal is %6d", total);
printf("\n\n\t\tAverage is %7.2f", average);
}
getchar();
}