繁体   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