繁体   English   中英

fscanf计算“不可见”空间

[英]fscanf counting “invisible” spaces

我目前正在研究从.txt文件获取信息并将其存储在矩阵中的程序。 当我仅打印文件时,请使用以下几行代码:

void read_maze(struct maze *mazePointer) {

FILE *fp;
fp = fopen("map1.txt", "r");

    int counter = 0;
    int column = 0;
    char mazeContent[99999];

    if(fp != NULL) {

        while (fscanf(fp, "%c", &mazeContent[counter]) == 1){

            int row = counter % 10;
            printf("%c", mazeContent[counter]);

            counter++;

            if (row == 9) {
                column ++;
            }               
        } 

        fclose(fp);
    }
}

请注意,即时消息我尚未使用“ row”和“ column”变量,这仅用于下一个示例! 从这行代码中,我得到以下输出:

##########
#    #   #
# ##   #S#
# ########
#       E#
##########

看起来不错,但只要将列和行变量添加到它们中,就需要将它们存储在矩阵中,这就是为什么我需要对列和行进行正确拟合的原因,得到以下输出。

#(0,0)#(0,1)#(0,2)#(0,3)#(0,4)#(0,5)#(0,6)#(0,7)#(0,8)#(0,9)
(1,0)#(1,1) (1,2) (1,3) (1,4) (1,5)#(1,6) (1,7) (1,8) (1,9)#(2,0)
(2,1)#(2,2) (2,3)#(2,4)#(2,5) (2,6) (2,7) (2,8)#(2,9)S(3,0)#(3,1)
(3,2)#(3,3) (3,4)#(3,5)#(3,6)#(3,7)#(3,8)#(3,9)#(4,0)#(4,1)#(4,2)
(4,3)#(4,4) (4,5) (4,6) (4,7) (4,8) (4,9) (5,0) (5,1)E(5,2)#(5,3)
(5,4)#(5,5)#(5,6)#(5,7)#(5,8)#(5,9)#(6,0)#(6,1)#(6,2)#(6,3)#(6,4)

这不一样。 如您所见,当.txt文件中没有空格时,我的函数会在第2行的开头计算其余部分的空间。 由于我无法在矩阵中的指定位置签署数字,因此这完全弄乱了一切。 有谁知道出了什么问题,因为不幸的是我找不到它。

从“ fgets” while循环开始就可以了!

    if(fp != NULL) {
            while (fgets(line, 12, fp) != NULL){

                for(int indexChar = 0; indexChar < 10; indexChar ++) {
                    printf("%c(%i)", line[indexChar], indexChar);
                }
                printf("\n");           
            } 
            fclose(fp);
    }

输出:

#(0)#(1)#(2)#(3)#(4)#(5)#(6)#(7)#(8)#(9)
#(0) (1) (2) (3) (4)#(5) (6) (7) (8)#(9)
#(0) (1)#(2)#(3) (4) (5) (6)#(7)S(8)#(9)
#(0) (1)#(2)#(3)#(4)#(5)#(6)#(7)#(8)#(9)
#(0) (1) (2) (3) (4) (5) (6) (7)E(8)#(9)
#(0)#(1)#(2)#(3)#(4)#(5)#(6)#(7)#(8)#(9)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM