我遇到的问题是使用标准输入从文件中读取多行整数.文件看起来像:
123
423
235
523
..etc
Run Code Online (Sandbox Code Playgroud)
我目前的代码是:
/*
* 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;
}
}
Run Code Online (Sandbox Code Playgroud)
我试图使用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
Run Code Online (Sandbox Code Playgroud)
运行我的测试错误:
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
Run Code Online (Sandbox Code Playgroud)
你有两个问题:
首先,您将跳过文件中的一堆行,因为您在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;
}
Run Code Online (Sandbox Code Playgroud)
其次,您希望将每个整数读取为单独的字符,即.%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);
Run Code Online (Sandbox Code Playgroud)
更新2:
另请查看ladenedge注释我的答案有关对整数值使用宽度说明符,而不是读入字符并转换它们.
| 归档时间: |
|
| 查看次数: |
4910 次 |
| 最近记录: |