Consider a simple program. It must take sequences of 5 numbers from stdin and print their sums. It is not stated how many lines of input will be taken, but program must terminate if newline character is taken twice (or Enter is pressed twice).
For example,
Input:
1 1 1 1 1
2 2 2 2 2
3 3 3 3 3/n
/n
Output:
5
10
15
#include <stdio.h>
int main()
{
int n1, n2, n3, n4, n5;
int sum;
while (/*condition*/)
{
scanf ("%d %d %d %d %d\n", &n1, &n2, &n3, &n4, &n5);
sum = n1 + n2 + n3 + n4 + n5;
printf ("%d\n", sum);
}
return 0;
}
The only problem is I don't know what condition must be in a while-loop. A little bit of help will be appreciated.
Thanks in advance.
Use
getc(stdin)
(man page) to read a single character fromstdin
, if it isn't a newline you can put it back withungetc(ch, stdin)
(man page) and usescanf
to read your number.Online demo: http://ideone.com/y99Ns6
Well, you could simply put the scanf call in the condition, and check if it succeeded in setting your variables.
(Couldn't test this code myself)