gpt4 book ai didi

c - 如何扫描文件中的某些字符

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

我目前正在研究数独验证器,我这样做的方法是将每一行分成一个长度为 9 的数组并检查,将每一列分成一个长度为 9 的数组并检查,等等。我已经完成了这些行已经在做这样的事情了

         for( i=0; i<9; i++)
fscanf(file, "%1d", &row1[i]);
for( i=0; i<9; i++)
fscanf(file, "%1d", &row2[i]);
for( i=0; i<9; i++)
fscanf(file, "%1d", &row3[i]);
for( i=0; i<9; i++)
fscanf(file, "%1d", &row4[i]);

它也按照我想要的方式工作。

我的数独解决方案中的每个数字在水平方向上由一个空格分隔,在我的文件中垂直方向上彼此相邻。

但是,我在尝试将每一列扫描到数组中时遇到了问题。基本上我认为我需要做的是第一列从第一个(左上角)字符开始并将其存储到数组的第一个插槽中。然后我需要跳过 9 个字符,然后存储那个字符。

我以为我可以做类似的事情

         for( i=0; i<82; i += 9)
fscanf(file, "%1d", &col1[i]);
for( i=1; i<82; i+=9)
fscanf(file, "%1d", &col2[i]);
for( i=2; i<82; i+=9)
fscanf(file, "%1d", &col3[i]);
for( i=3; i<82; i+=9)
fscanf(file, "%1d", &col4[i]);
for( i=4; i<82; i+=9)

但我意识到它不起作用,因为我已将我的数组大小设置为 9,并且由于我插入到数组中的第 i 个值中,这不会像它想要的那样运行。

谁能给我一个建议,我该如何实现它?我认为这相当微不足道,但我很难理解它。

谢谢

编辑:我还需要为该区域执行此操作,所以我基本上是在寻找一种方法来跳过文件并仅存储我想要的某些字符。

最佳答案

因为它是一个数独验证器,所以创建一个 9 * 9 二维数组并像您正在做的那样逐行读取。然后逐行或逐列循环以验证您的数独方 block 。

// As pointed out in comments, this code assumes you have a minimum of 9*9 separated ints with width = 1.
// If not, you need to check whether fscanf failed or not.
int sudoku[9][9] ;
for(int i = 0; i < 9; ++i)
for(int j = 0; j < 9; ++j)
fscanf(file_ptr, "%1d", &sudoku[i][j]); /* Check for the return value
* of fscanf if it is not
* guaranteed that there
* will always be 81 elements
* to read from or some other
* error occurred while
* reading the file.
*/

// now use sudoku to verify.
for(int i = 0; i < 9; ++i)
for(int j = 0; j < 9; ++j)
{
// sudoku[i][j] is row wise.
// sudoku[j][i] is column wise.
}

我假设您使用的是 C99 或更高版本的编译器。如果是C89,需要把int iint j声明移到函数开头(循环外)。

关于c - 如何扫描文件中的某些字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28464615/

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