Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: Read from stdin until Enter is pressed twice

Tags:

c

io

stdin

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.

like image 945
Kudayar Pirimbaev Avatar asked Mar 26 '13 11:03

Kudayar Pirimbaev


2 Answers

Use getc(stdin) (man page) to read a single character from stdin, if it isn't a newline you can put it back with ungetc(ch, stdin) (man page) and use scanf to read your number.

int main() {
    int sum = 0;
    int newlines = 0;
    int n = 0;
    while(1) {
        int ch = getc(stdin);
        if(ch == EOF) break;
        if(ch == '\n') {
            newlines++;
            if(newlines >= 2) break;
            continue;
        }

        newlines = 0;
        ungetc(ch, stdin);
        int x;
        if(scanf("%d", &x) == EOF) break;
        sum += x;
        n++;
        if(n == 5) {
            printf("Sum is %d\n", sum);
            n = 0;
            sum = 0;
        }
    }
}

Online demo: http://ideone.com/y99Ns6

like image 131
Jacob Parker Avatar answered Sep 21 '22 10:09

Jacob Parker


Well, you could simply put the scanf call in the condition, and check if it succeeded in setting your variables.

#include <stdio.h>

int main()
{
    int n1, n2, n3, n4. n5;
    int sum;
    while (scanf ("%d %d %d %d %d\n", n1, n2, n3, n4, n5) != EOF)
    {
        sum = n1 + n2 + n3 + n4 + n5;
        printf ("%d\n", sum);
    }
    return 0;
}

(Couldn't test this code myself)

like image 45
Miklos Aubert Avatar answered Sep 22 '22 10:09

Miklos Aubert