gpt4 book ai didi

C从文件中读取多行

转载 作者:太空宇宙 更新时间:2023-11-04 00:55:10 25 4
gpt4 key购买 nike

我遇到的问题是使用标准输入从文件中读取多行整数。这些文件看起来像:

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,并将这些字符代码转换为整数值。 IE。 subtract ((int)ch - 48) 其中 ch 是 fscanf 读取的字符之一。

更新:

您还向 fscanf 传递了错误的值,您想传递变量的内存位置而不是它们的值。

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

更新 2:

另请查看 ladenedge 对我关于使用整数值的宽度说明符而不是读取字符并转换它们的回答的评论。

关于C从文件中读取多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5408700/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com