Search code examples
cparsinginputstdinscanf

Reading input from stdin until empty line


I want to parse input such as:

1 2 3\n4 5 6\n7 8 9\n\n

and for each row save each value in int ant print it to stdout until I get an empty line, so for this example I would get:

1 2 3
1 2 3
4 5 6
4 5 6
7 8 9
7 8 9

I've tried something like

int n1, n2, n3;
while(scanf ("%d %d %d\n", n1, n2, n3) != EOF) {
    printf("%d %d %d\n", n1, n2, n3);
    fflush(stdout);
}

but it doesn't seem to work. Is there any simple way to do that?


Solution

  • scanf cannot achieve what you are trying to do because it keeps reading until the condition is met, and %d specifier will ignore '\n' newline character, I propose this code

    #include <stdio.h>
    #include <string.h>
    
    int  main()
    {
        int n1, n2, n3;
        char line[64];
    
        /* read at least 63 characters or unitl newline charater is encountered with */
        /*    fgets(line, sizeof line, stdin) */
        /* if the first character is a newline, then it's an empty line of input */
        while ((fgets(line, sizeof line, stdin) != NULL) && (line[0] != '\n'))
        {
            /* parse the read line with sscanf */
            if (sscanf(line, "%d%d%d", &n1, &n2, &n3) == 3)
            {
                printf("%d %d %d\n", n1, n2, n3);
                fflush(stdout);
            }
        }
        return 0;
    }
    

    While this code works it's not robust, since it will fail in the case commented below by WhozCraig, so this is a way to do it that will keep you safe from the problem

    #include <stdio.h>
    #include <string.h>
    #include <ctype.h> /* for isspace */
    
    int isEmpty(const char *line)
    {
        /* check if the string consists only of spaces. */
        while (*line != '\0')
        {
            if (isspace(*line) == 0)
                return 0;
            line++;
        }
        return 1;
    }
    
    int  main()
    {
        int n1, n2, n3;
        char line[64];
    
        while ((fgets(line, sizeof line, stdin) != NULL) && (isEmpty(line) == 0))
        {
            if (sscanf(line, "%d%d%d", &n1, &n2, &n3) == 3)
            {
                printf("%d %d %d\n", n1, n2, n3);
                fflush(stdout);
            }
        }
        return 0;
    }