0

I'm supposed to read some variables named from "A" to "Z" and then evaluate them. The values in variables are matrices. This is example input:

B=[5 2 4; 0 2 -1; 3 -5 -4]
E=[-6 -5 -8; -1 -1 -10; 10 0 -7]
R=[-1 -7 6; -2 9 -4; 6 -10 2]

R+E+B

I have written an algorithm that correctly reads all the variables. However I fail at detecting the empty line. I have written this:

// FILE* input = stdin; 
while(true) {
    char name = '#';
    // Reads the matrix, returns null on error
    Matrix* A = matrix_read_prp_2(input, &name);
    if( A==NULL ) {
        // throw error or something
    }
    // Print the matrix
    matrix_print_prp_2(A, stdout);
    // consume one new line
    char next;
    if(fscanf(input, "\n%c", &next)!=1)
        // Program returns error here
    if(next=='\n')
        break;
    // if not new line, put the char back
    // and continue
    ungetc(next, input);
}

I assumed that for empty line, fscanf(input, "\n%c", &next) would read '\n' into next, but it actually skips the second line and reads R.

How can I check if next line is empty on stream in C?

Tomáš Zato
  • 50,171
  • 52
  • 268
  • 778
  • 3
    It is very, very hard to detect newlines of any sort with `scanf()` and friends. If you need to detect empty lines, then use `fgets()` or equivalent to read the material, and `sscanf()` to analyze the lines after you know it isn't empty. Any white space in a `scanf()` format string matches a sequence of zero or more white space characters; newlines, blanks, tabs are all white space. The newline in `"\n%c"` skips white space until the next character isn't white space. – Jonathan Leffler Nov 27 '16 at 02:00

1 Answers1

1

If it is safe to assume that the matrix_read_prp_2() function leaves the newline in the input buffer, then it would be possible to revise I/O operations in the tail of the loop along these lines:

    // Read anything left over to end of line
    int c;
    while ((c = getc(input)) != EOF && c != '\n')
        ;
    // Break on EOF or second newline
    if (c == EOF || (c = getc(input)) == EOF || c == '\n')
        break;
    // if not new line, put the char back and continue
    ungetc(c, input);
}

Untested code.

I'm not clear under what circumstances the nasrat(mgr, op); function call should be made; neither mgr nor op appears in the loop.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • I used similar solution with slightly more verbose code that does the same thing. Thanks for answer. The `nasrat` function was used to `exit()` the program, the arguments passed to it were memory managers which were cleaned up before exiting. I removed it from the question. The reason it was called is that it is indeed safe to assume that when `matrix_read_prp_2` ends, there should be new line in the buffer, lest the input is invalid. – Tomáš Zato Nov 27 '16 at 12:30