2

In the following code, I'm attempting to store all characters from a file (including newlines). If a newline is read, variable 'i' should be incremented and 'j' reset to 0, but this doesn't happen. I've confirmed that the newlines are in fact being read and stored, by printing from my array to console.

void scan_solved_nonogram(board *b) {
  FILE *file = fopen("test.txt", "r");

  int i = 0, j = 0;
  while( ( b->symbol[i][j] = getc(file) ) != EOF ) {
    j++;

    if( b->symbol[i][j] == '\n' ) {
      i++;
      j = 0;
    }
  }

  fclose(file);

  b->size_i = i;
  b->size_j = j;

}
kensing
  • 95
  • 1
  • 1
  • 8
  • 3
    one suggestion instead of `while( ( b->symbol[i][j] = getc(file) ) != EOF )`, Use a **int** variable for eample `int ch; and change while like `while( ( c = getc(file) ) != EOF )` Now in while `{}` check `ch` against `\n` – Grijesh Chauhan Jul 15 '13 at 14:49
  • I assume that symbol is an two dimensional array of char. Did you confirm that you were getting a 0xA character(newline)? – Tarik Jul 15 '13 at 14:51

1 Answers1

8

The problem is that you increment j before you check for the newline character.

while( ( b->symbol[i][j] = getc(file) ) != EOF ) {
    j++;// you increment j, so you need to check for newline at j-1

    if( b->symbol[i][j-1] == '\n' ) {
      i++;
      j = 0;
    }
  }
jh314
  • 27,144
  • 16
  • 62
  • 82