Reputation: 85
#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
Upvotes: 0
Views: 11151
Reputation: 144550
Your while
loop is fine, the program loops until it hits the end of file for stdin
. From the terminal, you can signal an end of file by pressing Ctrl-D under Unix and Ctrl-Z Enter on Windows.
Alternately, you could exit the loop when you read some specific input, such as a blank line, a line without a number, a line with the word quit
...
Some remarks about the program:
stdin
.for (;;) { ... }
.main()
should return 0.Here is a modified version of your program:
#include <stdio.h>
#define LINESIZE 1024
int main(void) {
char line[LINESIZE];
int n, sum = 0;
for (;;) {
printf("enter an integer: ");
if (!fgets(line, sizeof line, stdin)) {
break;
}
if (*line == '\n') {
/* stop on empty line */
break;
}
if (!strcmp(line, "quit\n")) {
/* stop if the user types quit */
break;
}
if (sscanf(line, "%d", &n) == 1) {
sum += n;
}
}
printf("%d\n", sum);
return 0;
}
Upvotes: 3
Reputation: 1395
In addition to the comments mentioned in the question, I would like to suggest a slightly different approach. You can modify the if
statement which calculates the sum
such that when the input from the user is not an int
eger, you choose to exit the while loop.
if (sscanf(line, "%d", &n) == 1) {
sum += n;
}
else {
printf("Could not get integer\n");
break;
}
Sample output 1:
enter an integer:
3
enter an integer:
4
enter an integer:
2
enter an integer:
r
Could not get integer
9
Sample output 2: sscanf successfully extracted 5 from 5gf
enter an integer:
3
enter an integer:
4
enter an integer:
5gf
enter an integer:
t
Could not get integer
12
Sample output 3: sscanf could not extract 5 from r5f and rightly so
enter an integer:
5
enter an integer:
3
enter an integer:
r5f
Could not get integer
8
Upvotes: 0