C从文件中读取多行

时间:2011-03-23 16:42:55

标签: c stdio scanf

我遇到的问题是使用标准输入从文件中读取多行整数。文件如下:

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,因为文件格式正确(根据函数configure上面的注释)但我无法使用它。

如果有一种不同的,更简单的方法来解决这个很难看的解决方案。

语言: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

3 个答案:

答案 0 :(得分:5)

您正在做的事情有两个问题:

首先,您将跳过文件中的一堆行,因为您在while循环中调用fscanf,然后在检查循环条件后立即调用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,并将这些字符代码转换为整数值。即。 subtract((int)ch - 48)其中ch是fscanf读入的字符之一。

更新:

您也将错误的值传递给fscanf,您希望传递变量的内存位置而不是其值。

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

更新2:

同时检查ladenedge注释我的答案有关对整数值使用宽度说明符,而不是读入字符并转换它们。

答案 1 :(得分:1)

警告清楚地表明在运行时可能出现的问题 -

 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

答案 2 :(得分:0)

作为一个好习惯,总是使用伪代码!看看上面的谜题/规范,我会做类似的事情:

  1. 打开文件
  2. 抓住第一行(它可能是一个字符串)而你不在EOF
  3. 将3位数字分成单独的变量
  4. puzzle [num1] [num2] = num3
  5. fixed [num1] [num2] = 1
  6. 转到#2
  7. 因为我没有完全检查规格,所以可能会在一两个地方关闭。