Haroonie, the way you are reading the text forces the program to keep reading when they are no more inputs thus it would simply use the previous fgets() result since you are not using the value of fgets() to terminate the loop once an EOF occurs. So something like this should suffice:
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
FILE *fp;
int array1[3];
int linect = 0;
int linesum = 0;
char buf[128];
fp = fopen("numbers.txt", "r");
if(fp == NULL)
{
fprintf(stderr,"Cannot open file for reading");
exit(EXIT_FAILURE);
}
while( fgets(buf,sizeof(buf),fp) != NULL )
{
sscanf(buf, "%d %d %d", &array1[0], &array1[1], &array1[2]);
printf("Set %d - 1st: %d, 2nd: %d, 3rd: %d", linect, array1[0], array1[1], array1[2]);
linesum = (array1[0] + array1[1] + array1[2]);
printf(" Line Sum = %d \n", linesum);
linect++;
}
if(fclose(fp) != 0)
{
fprintf(stderr,"Could not close file properly!\n");
exit(EXIT_FAILURE);
}
return 0;
}
You should also check the fclose() return value, and I've also taken out your last few lines for input - run the program in a terminal so you don't need those lines. Otherwise just add it in like you did before.