Tomáš Zato Tomáš Zato - 10 days ago 7
C Question

Finding empty line using fscanf

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?

Answer

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.