Вопрос

So I'm writing a parallelized sudoku solution checker in C, but I seem to be encountering an issue with reading in a plain old .txt file.

Here is the code to read in the file:

FILE* fp = fopen(argv[1], "r");
if (fp == NULL) {
    printf("Cannot open file\n");
    return 1;
}

//Begin copying file using fgetc
int c;
while ((c = fgetc(fp)) != EOF) {
    for (int i = 0; i < PUZZLE_SIZE; ++i) {
        for (int j = 0; j < PUZZLE_SIZE; ++j) {
            if (c != -38) { //-38 is newline
                //puzzle is a global array of ints
                puzzle[i][j] = c - 48; //handles ASCII to int (1-9) conversion
            }
        }
    }
}
fclose(fp);

The .txt file is as follows:

534678912
672195348
198342567
859761423
426853791
713924856
961537284
287419635
345286179

When I print c - 48, I get the expected values; when I print puzzle[i][j] inside of the loops, I get the normal values again. However, when I look at my puzzle array afterward, every value is set to 9; I cannot, for the life of me, figure out why. Is there a memory/scoping issue that I'm not aware of?

Это было полезно?

Решение

Basically, what your program does is: For every character in the file (while), set ALL (for, for) puzzle entries to that character. As a result, all entries will contain the file's last character.

You want to put the for loops on the outside and read one character per puzzle entry instead:

for (int i = 0; i < PUZZLE_SIZE; ++i)
    for (int j = 0; j < PUZZLE_SIZE; ++j) {
        c = fgetc(fp);
        if (c == '\n')
            c = fgetc(fp); // get a new char if we hit a newline
         puzzle[i][j] = c - `0`;
    }

This is assuming that there are enough characters in the file to fill the puzzle.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top