#include<stdio.h>
#define LINESIZE 1024
int n, sum =0;
char line[LINESIZE];
int main() {
while(1) {
printf("enter an integer: ");
if(!fgets(line, LINESIZE, stdin)) {
clearerr(stdin);
break;
}
if (sscanf(line, "%d", &n) == 1)
sum += n;
}
printf("%d \n",sum);
}
When I run this in Cygwin, the output seems infinite and I don't know how to return sum? Am I missing something?
enter an integer: 1
enter an integer: 2
enter an integer: 3
enter an integer: 4
enter an integer: 5
enter an integer: 6
fgetsto return 0? It will only return the null pointer when it encounters the end of file marker, i.e.CTRL-Dfgets()will block, waiting for input. When reading from stdin, the is only one way to handle the problem. I.E. pass the program in End Of File indication. for cygwin, that is a<ctrl-d>