簡體   English   中英

C從文件中讀取多行

[英]C reading in multiple lines from file

我的問題是使用標准輸入從文件中讀取多行整數。 這些文件如下所示:

123
423
235
523
..etc

我目前的代碼是:

/*
 * Read in the initial puzzle configuration.
 * Each line is 4 characters long:
 *   Row    as a character '0' .. '9'
 *   Column as character '0' .. '9'
 *   Digit  as character '0' .. '9'
 *   Terminating newline.
 * Exits with an error message if there are syntactic
 * or semantic errors with any configuration line.
 */

void configure(FILE *puzzle_file) {
        int row;
        int column;
        int value;

        while((fscanf(puzzle_file, "%i%i%i\n", row, column, value)) != EOF){
                fscanf(puzzle_file, "%i%i%i\n", row, column, value);
                puzzle[row][column] = value;
                fixed[row][column] = 1;
        }

}

我正在嘗試使用fscanf,因為文件格式正確(根據配置函數上方的注釋),但是我無法使其正常工作。

如果有另一種更輕松的方法來解決此解決方案,那將很有趣。

語言:C

編輯:

關於編譯錯誤:

xxxxxxx@linus:~/350/sudoku$ make
gcc -c puzzle.c
puzzle.c: In function ‘configure’:
puzzle.c:95: warning: format ‘%i’ expects type ‘int *’, but argument 3 has type ‘int’
puzzle.c:95: warning: format ‘%i’ expects type ‘int *’, but argument 4 has type ‘int’
puzzle.c:95: warning: format ‘%i’ expects type ‘int *’, but argument 5 has type ‘int’
puzzle.c:96: warning: format ‘%i’ expects type ‘int *’, but argument 3 has type ‘int’
puzzle.c:96: warning: format ‘%i’ expects type ‘int *’, but argument 4 has type ‘int’
puzzle.c:96: warning: format ‘%i’ expects type ‘int *’, but argument 5 has type ‘int’
gcc -o sudoku main.o puzzle.o arguments.o

運行我的測試錯誤:

xxxxxxx@linus:~/350/sudoku$ make test_l2 
./sudoku -e p+s/good_puzzle.txt < p+s/script_good_quit.txt
/bin/sh: line 1:  9143 Segmentation fault      ./sudoku -e p+s/good_puzzle.txt < p+s/script_good_quit.txt
make: *** [good_configured] Error 139

您在做什么有兩個問題:

首先,您將跳過文件中的許多行,因為在while循環中調用fscanf,然后在檢查循環條件之后立即執行。 您只需要在while循環條件中調用一次即可。

    while((fscanf(puzzle_file, "%i%i%i\n", row, column, value)) != EOF){
            // fscanf(puzzle_file, "%i%i%i\n", row, column, value);  REMOVE THIS!
            puzzle[row][column] = value;
            fixed[row][column] = 1;
    }

其次,您需要將每個整數讀取為單獨的字符,即。 %c%c%c而不是%i%i%i ,然后將這些字符代碼轉換為整數值。 即。 減去((int)ch-48),其中ch是fscanf讀取的字符之一。

更新:

您還將錯誤的值傳遞給fscanf,想要傳遞變量的內存位置而不是其值。

char row,value,column;
fscanf(puzzle_file, "%c%c%c\n", &row, &column, &value);

更新2:

還要檢查關於我的答案的ladenedge評論,該評論關於對整數值使用寬度說明符,而不是讀取字符並進行轉換。

該警告明確表明在運行時可能出了什么問題-

 puzzle.c:95: warning: format ‘%i’ expects type ‘int *’, but argument 3 has type ‘int’

所以改變

(fscanf(puzzle_file, "%i%i%i\n", row, column, value)

(fscanf(puzzle_file, "%i%i%i\n", &row, &column, &value)
// Added & symbol

作為一個好習慣,請始終使用偽代碼! 看看上面的難題/規格,我會做類似的事情:

  1. 打開文件
  2. 當您不在EOF時,抓住第一行(可能是字符串)
  3. 將3位數字分成單獨的變量
  4. 拼圖[num1] [num2] = num3
  5. 固定的[num1] [num2] = 1
  6. 轉到#2

由於我沒有完全檢查規格,所以可能在一兩個地方放過。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM