C语言,如何将文件中的值转换为二维数组

时间:2022-07-22 13:33:10

I have a file with random characters in basically a word search format. i would like to be able to take all the characters in it and put it into a 2d puzzle array so that i am able to type something like printf("the value is %c",puzzle[2][2]); and it will print the value in the 3rd row and 3rd column (since it starts at 0...) heres my code so far.

我有一个带有随机字符的文件,基本上是一个单词搜索格式。我希望能够将其中的所有字符放入2d拼图数组中,这样我就可以输入printf(“值为%c”,puzzle[2][2]);它将在第3行和第3列中打印值(因为它从0开始…)

#define MAXROWS     60
#define MAXCOLS     60
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>

main() {
    char TableFileName[100];
    char PuzzleFileName[100];
    char puzzle[MAXROWS][MAXCOLS];
    char line[MAXCOLS];
    FILE *TableFilePtr;
    int cols = 0;
    int rows = 0;
    printf("Please enter the table file name: ");
    scanf("%s",TableFileName);

    /* ... */

    TableFilePtr = fopen(TableFileName, "r");

    while (fgets(line, sizeof line, TableFilePtr) != NULL && rows < MAXROWS) {
        for (cols; cols<(strlen(line)-1) && cols < MAXCOLS; ++cols) {
            puzzle[rows][cols] = line[cols];
        }
        ++rows;
    }
    printf("%c",puzzle[2][2]);
}

the puzzle[x][y] doesnt contain any values once the program runs. any ideas?

当程序运行时,谜题[x][y]不包含任何值。什么好主意吗?

update1: changed for cols to for cols=0 update2: added printf("\nthe rows are at %d, cols at %d, puzzle[%d,%d]=%c line[cols]=%c",rows,cols,rows,cols,puzzle[rows,cols],line[cols]); to for loop update3: after update 2, i see the line[cols] characters are getting every character in the puzzle, but not int the correct order. also, the line[cols] isnt correctly being put into the puzzle[rows][cols]. heres some of what what im seeing (not sure why its making me put it as code but whatever):

更新1:cols改为cols=0 update2:添加printf(“\nthe rows are at %d, cols at %d, puzzle[%d,%d]=%c line[cols]=%c”,row,cols,row,cols,puzzle[rows,cols],line[cols];对于循环更新3:在更新2之后,我看到行[cols]字符获得了拼图中的每个字符,但不是正确的顺序。而且,这行[cols]并没有被正确地放入拼图[row][cols]中。以下是我看到的一些东西(不知道为什么我把它当成代码来写):

the rows are at 0, cols at 0, puzzle[0,0]=l line[cols]=A
the rows are at 0, cols at 1, puzzle[0,1]=▒ line[cols]=
the rows are at 0, cols at 2, puzzle[0,2]=▒ line[cols]=B
the rows are at 0, cols at 3, puzzle[0,3]=  line[cols]=
the rows are at 0, cols at 4, puzzle[0,4]=\ line[cols]=D
the rows are at 0, cols at 5, puzzle[0,5]=▒ line[cols]=
the rows are at 0, cols at 6, puzzle[0,6]=▒ line[cols]=E
the rows are at 0, cols at 7, puzzle[0,7]= line[cols]=
the rows are at 0, cols at 8, puzzle[0,8]=L line[cols]=Q
the rows are at 0, cols at 9, puzzle[0,9]=▒ line[cols]=
the rows are at 0, cols at 10, puzzle[0,10]=▒ line[cols]=T

the A,B,D,E,A,T are correct but... A should be puzzle[0,0], B should be [0,1] D should be [0,2] etc...

A B D E A T是正确的但是…A应该是拼图[0,0],B应该是[0,1]D应该是[0,2]等等…

heres a sampler of the input... (would be in a txt file)

这是一个输入的采样器。(在txt文件中)

K N R D J P L H X E K B W M X A M U Y A L E F Q N D L D  
B D B S W W M T F B K Z D G A L V L K U N U R C R I E I  
H N L A N D N T O V P O G R U U Y X E D L Y R M Q D T T  
Y C G Y E M A S I E X P V Z N W H X B D G G R T K V C W  
M Y C X A M I E U T Z J U O C N F F L R E F B T D R Y W  
R K V A C B H G L C F D Y X R Z Q E R E H N Q D S J H T  
R G E N Y Y K F J V G S C G D H O G K A F E M I S S Q P 
S J Z A B V A A P E E P R K F T A H W C G B J N N L W B 
F V F Z Y T V Y E O C Y A D L Q Q P P F V W K M E U V O 

3 个解决方案

#1


0  

when I run your code, I am getting real values from my text file in the puzzle array. I think you're just mistaken about where you're putting those values. I can't be sure what you're doing since you didn't include an example of what you're parsing, but I'm definitely getting values in my puzzle array.

当我运行您的代码时,我正在从困惑数组中的文本文件中获取真正的值。我认为你只是在放这些值的地方弄错了。我不确定您在做什么,因为您没有包含要解析的示例,但是我肯定会在我的迷惑数组中获取值。

if my file looks like this : 1 2 3 4 5 6 7 8 9 10 then the first three elements of puzzle[0] are "1", " ", "2" and all other elements of puzzle are null.

如果我的文件是这样的:1 2 3 4 5 6 7 8 9 10那么谜题[0]的前三个元素是“1”,“”,“2”,所有其他的迷题元素都是空的。

After playing around for a bit I realized what seems to be the problem. You've declared cols up top, and it's being reused inside the loop. So when rows gets incremented, you're not resetting cols. Add cols = 0; after rows++ and the array seems to behave the way you need it to.

玩了一会儿之后,我意识到问题出在哪里。您已经声明了cols的顶部,并且它在循环中被重用。所以当行递增时,你不会重置cols。添加关口= 0;行++ +之后,数组的行为看起来就像你需要的那样。

Edit: mostly style things.

编辑:主要风格的事情。

For one thing, you're using a for loop inside of a while loop, which seems strange to me for iterating over a multidimensional array. Don't get me wrong- they're basically the same thing. But for readability, it usually makes more sense to me to do while(while) or for(for) when you're doing something like this with rows and columns.

首先,您在while循环中使用了一个For循环,对我来说,在多维数组上进行迭代很奇怪。别误会我的意思——他们基本上是一回事。但是对于可读性来说,当(while)或for(for)处理这样的行和列时,对我来说更有意义。

Also, instead of resetting cols and incrementing rows at the end of the while loop, try changing it to a for loop. If you declare the incrementers in the declaration of the for loop, you won't have to worry as much about making these mistakes, and it becomes more readable IMO.

另外,不要在while循环结束时重新设置cols和增加行,而是尝试将其更改为for循环。如果您在for循环的声明中声明了增量,那么您就不需要担心犯这些错误,而且在IMO上它会变得更加可读。

Also, one last note for now - maybe the thing you didn't realize was that you have to be very careful using sizeof on a char array. I wouldn't use sizeof as the maxint for fgets, as sizeof includes the null terminator in a char array (see this post C++: size of a char array using sizeof)

还有,最后一个注意事项——可能您没有意识到的是,在char数组中使用sizeof时必须非常小心。我不会将sizeof用作fgets的maxint,因为sizeof在char数组中包含了空终止符(参见下面的文章c++:使用sizeof的char数组的大小)

I'm not a c expert so there's probably a lot more to be said here (there are a ton of ways to get lines from a file and I don't think fgets is the reccomended route) but that's about all I can think of for now, and it will hopefully at least help you get it running properly.

我不是一个c专家所以这里可能更多的是说(有很多方法可以得到行函数从一个文件中,我不认为是推荐的路线),但这是我能想到的现在,它至少会希望帮助你获得正常运行。

#2


0  

test.c

test.c

#define MAXROWS     60
#define MAXCOLS     60
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>

main()
{
char TableFileName[100];
char PuzzleFileName[100];
char puzzle[MAXROWS][MAXCOLS];
char line[MAXCOLS];
FILE *TableFilePtr;
int cols;
int rows;
cols=0;
rows=0;
printf("Please enter the table file name: ");
scanf("%s",TableFileName);

TableFilePtr = fopen(TableFileName, "r");

while (fgets(line, sizeof line, TableFilePtr) != NULL && rows < MAXROWS) {
    char *p=line;
    for(cols=0;NULL != (p=strtok(p, " \n")) && cols < MAXCOLS; ++cols){
        puzzle[rows][cols]=*p;
        p=NULL;
    }
    ++rows;
}
{   //check puzzle[][] print out
    int r, c;
    for(r=0;r<rows;r++){
        for(c=0;c<cols;c++){
            printf("%c", puzzle[r][c]);
        }
        printf("\n");
    }
}
printf("%c",puzzle[2][2]);
}

data.txt

data.txt

K N R D J P L H X E K B W M X A M U Y A L E F Q N D L D  
B D B S W W M T F B K Z D G A L V L K U N U R C R I E I  
H N L A N D N T O V P O G R U U Y X E D L Y R M Q D T T  
Y C G Y E M A S I E X P V Z N W H X B D G G R T K V C W  
M Y C X A M I E U T Z J U O C N F F L R E F B T D R Y W  
R K V A C B H G L C F D Y X R Z Q E R E H N Q D S J H T  
R G E N Y Y K F J V G S C G D H O G K A F E M I S S Q P 
S J Z A B V A A P E E P R K F T A H W C G B J N N L W B 
F V F Z Y T V Y E O C Y A D L Q Q P P F V W K M E U V O 

execute program result:

程序执行结果:

Please enter the table file name: data.txt
KNRDJPLHXEKBWMXAMUYALEFQNDLD
BDBSWWMTFBKZDGALVLKUNURCRIEI
HNLANDNTOVPOGRUUYXEDLYRMQDTT
YCGYEMASIEXPVZNWHXBDGGRTKVCW
MYCXAMIEUTZJUOCNFFLREFBTDRYW
RKVACBHGLCFDYXRZQEREHNQDSJHT
RGENYYKFJVGSCGDHOGKAFEMISSQP
SJZABVAAPEEPRKFTAHWCGBJNNLWB
FVFZYTVYEOCYADLQQPPFVWKMEUVO
L

#3


-1  

while (fgets(line, sizeof line, TableFilePtr) != NULL && rows < MAXROWS) {
/*
    for (cols=0; cols<(strlen(line)-1) && cols < MAXCOLS; ++cols) {
        puzzle[rows][cols] = line[cols];
    }
*/
    char *p=line;
    for(cols=0;NULL != (p=strtok(p, " \n")) && cols < MAXCOLS; ++cols){
        puzzle[rows][cols]=*p;
        p=NULL;
    }
    ++rows;
}

test print code sample:

测试打印代码示例:

{   //check puzzle[][] print out
    int r, c;
    for(r=0;r<rows;r++){
        for(c=0;c<cols;c++){
            printf("%c", puzzle[r][c]);//do you mistake like this puzzle[r,c] ?
        }
        printf("\n");
    }
}

#1


0  

when I run your code, I am getting real values from my text file in the puzzle array. I think you're just mistaken about where you're putting those values. I can't be sure what you're doing since you didn't include an example of what you're parsing, but I'm definitely getting values in my puzzle array.

当我运行您的代码时,我正在从困惑数组中的文本文件中获取真正的值。我认为你只是在放这些值的地方弄错了。我不确定您在做什么,因为您没有包含要解析的示例,但是我肯定会在我的迷惑数组中获取值。

if my file looks like this : 1 2 3 4 5 6 7 8 9 10 then the first three elements of puzzle[0] are "1", " ", "2" and all other elements of puzzle are null.

如果我的文件是这样的:1 2 3 4 5 6 7 8 9 10那么谜题[0]的前三个元素是“1”,“”,“2”,所有其他的迷题元素都是空的。

After playing around for a bit I realized what seems to be the problem. You've declared cols up top, and it's being reused inside the loop. So when rows gets incremented, you're not resetting cols. Add cols = 0; after rows++ and the array seems to behave the way you need it to.

玩了一会儿之后,我意识到问题出在哪里。您已经声明了cols的顶部,并且它在循环中被重用。所以当行递增时,你不会重置cols。添加关口= 0;行++ +之后,数组的行为看起来就像你需要的那样。

Edit: mostly style things.

编辑:主要风格的事情。

For one thing, you're using a for loop inside of a while loop, which seems strange to me for iterating over a multidimensional array. Don't get me wrong- they're basically the same thing. But for readability, it usually makes more sense to me to do while(while) or for(for) when you're doing something like this with rows and columns.

首先,您在while循环中使用了一个For循环,对我来说,在多维数组上进行迭代很奇怪。别误会我的意思——他们基本上是一回事。但是对于可读性来说,当(while)或for(for)处理这样的行和列时,对我来说更有意义。

Also, instead of resetting cols and incrementing rows at the end of the while loop, try changing it to a for loop. If you declare the incrementers in the declaration of the for loop, you won't have to worry as much about making these mistakes, and it becomes more readable IMO.

另外,不要在while循环结束时重新设置cols和增加行,而是尝试将其更改为for循环。如果您在for循环的声明中声明了增量,那么您就不需要担心犯这些错误,而且在IMO上它会变得更加可读。

Also, one last note for now - maybe the thing you didn't realize was that you have to be very careful using sizeof on a char array. I wouldn't use sizeof as the maxint for fgets, as sizeof includes the null terminator in a char array (see this post C++: size of a char array using sizeof)

还有,最后一个注意事项——可能您没有意识到的是,在char数组中使用sizeof时必须非常小心。我不会将sizeof用作fgets的maxint,因为sizeof在char数组中包含了空终止符(参见下面的文章c++:使用sizeof的char数组的大小)

I'm not a c expert so there's probably a lot more to be said here (there are a ton of ways to get lines from a file and I don't think fgets is the reccomended route) but that's about all I can think of for now, and it will hopefully at least help you get it running properly.

我不是一个c专家所以这里可能更多的是说(有很多方法可以得到行函数从一个文件中,我不认为是推荐的路线),但这是我能想到的现在,它至少会希望帮助你获得正常运行。

#2


0  

test.c

test.c

#define MAXROWS     60
#define MAXCOLS     60
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>

main()
{
char TableFileName[100];
char PuzzleFileName[100];
char puzzle[MAXROWS][MAXCOLS];
char line[MAXCOLS];
FILE *TableFilePtr;
int cols;
int rows;
cols=0;
rows=0;
printf("Please enter the table file name: ");
scanf("%s",TableFileName);

TableFilePtr = fopen(TableFileName, "r");

while (fgets(line, sizeof line, TableFilePtr) != NULL && rows < MAXROWS) {
    char *p=line;
    for(cols=0;NULL != (p=strtok(p, " \n")) && cols < MAXCOLS; ++cols){
        puzzle[rows][cols]=*p;
        p=NULL;
    }
    ++rows;
}
{   //check puzzle[][] print out
    int r, c;
    for(r=0;r<rows;r++){
        for(c=0;c<cols;c++){
            printf("%c", puzzle[r][c]);
        }
        printf("\n");
    }
}
printf("%c",puzzle[2][2]);
}

data.txt

data.txt

K N R D J P L H X E K B W M X A M U Y A L E F Q N D L D  
B D B S W W M T F B K Z D G A L V L K U N U R C R I E I  
H N L A N D N T O V P O G R U U Y X E D L Y R M Q D T T  
Y C G Y E M A S I E X P V Z N W H X B D G G R T K V C W  
M Y C X A M I E U T Z J U O C N F F L R E F B T D R Y W  
R K V A C B H G L C F D Y X R Z Q E R E H N Q D S J H T  
R G E N Y Y K F J V G S C G D H O G K A F E M I S S Q P 
S J Z A B V A A P E E P R K F T A H W C G B J N N L W B 
F V F Z Y T V Y E O C Y A D L Q Q P P F V W K M E U V O 

execute program result:

程序执行结果:

Please enter the table file name: data.txt
KNRDJPLHXEKBWMXAMUYALEFQNDLD
BDBSWWMTFBKZDGALVLKUNURCRIEI
HNLANDNTOVPOGRUUYXEDLYRMQDTT
YCGYEMASIEXPVZNWHXBDGGRTKVCW
MYCXAMIEUTZJUOCNFFLREFBTDRYW
RKVACBHGLCFDYXRZQEREHNQDSJHT
RGENYYKFJVGSCGDHOGKAFEMISSQP
SJZABVAAPEEPRKFTAHWCGBJNNLWB
FVFZYTVYEOCYADLQQPPFVWKMEUVO
L

#3


-1  

while (fgets(line, sizeof line, TableFilePtr) != NULL && rows < MAXROWS) {
/*
    for (cols=0; cols<(strlen(line)-1) && cols < MAXCOLS; ++cols) {
        puzzle[rows][cols] = line[cols];
    }
*/
    char *p=line;
    for(cols=0;NULL != (p=strtok(p, " \n")) && cols < MAXCOLS; ++cols){
        puzzle[rows][cols]=*p;
        p=NULL;
    }
    ++rows;
}

test print code sample:

测试打印代码示例:

{   //check puzzle[][] print out
    int r, c;
    for(r=0;r<rows;r++){
        for(c=0;c<cols;c++){
            printf("%c", puzzle[r][c]);//do you mistake like this puzzle[r,c] ?
        }
        printf("\n");
    }
}