我有一个文本文件,在行和列中只是随机字母。所有我想做的是做一个二维数组,所以它是puzzle[i][j]
,如果我把printf("%c", puzzle[5][4]);
,它会简单地给我第4行和第3列的字符(因为它在数组中从0开始)。下面是我到目前为止的代码。
#define MAXROWS 60
#define MAXCOLS 60
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
main()
{
FILE *TableFilePtr;
char TableFileName[100];
char PuzzleFileName[100];
char puzzle[MAXROWS][MAXCOLS];
printf("Please enter the table file name: ");
scanf("%s",TableFileName);
TableFilePtr=fopen(TableFileName, "r");
if(TableFilePtr == NULL)
{
printf("Can't open %s", TableFileName);
exit(EXIT_FAILURE);
}
char words;
int n;
n=0;
int i,j,row,col;
int rowcount, colcount;
printf("n how many rows and colums are there? separate by a space: ");
scanf("%d %d",&row, &col);
/* while(fscanf(TableFilePtr,"%c",&words)!= EOF)
{
printf("%c",words);
}
*/
/*for (colcount=0;colcount<col;colcount++)
{
for (rowcount=0;rowcount<row;rowcount++)
{
printf("%c ",words);
}
printf("n");
}
*/
for(i=0;i<row;i++){
for(j=0;j<col;j++){
fscanf(TableFilePtr, "%c %sn",&puzzle[i]][j]);
//puzzle[i][j]=words;
// printf("%c ", puzzle[i][j]);
}
printf("n");
}
}
末尾的注释区域(只是开始部分)的作用是在编译器中简单地打印出文本文件。我想把它变成一个二维数组。
for(colcount=0;colcount<col;colcount++){...}
我会这样做(我没有使用所有变量的确切名称,但你知道的):
char puzzle[MAXROWS][MAXCOLS], line[MAXCOLS];
FILE *infile;
int cols = 0, rows=0;
/* ... */
infile = fopen(TableFileName, "r");
while(fgets(line, sizeof line, infile) != NULL)
{
for(cols=0; cols<(strlen(line)-1); ++cols)
{
puzzle[rows][cols] = line[cols];
}
/* I'd give myself enough room in the 2d array for a NULL char in
the last col of every row. You can check for it later to make sure
you're not going out of bounds. You could also
printf("%sn", puzzle[row]); to print an entire row */
puzzle[rows][cols] = ' ';
++rows;
}
编辑:更短的版本将有换行符和NULL字符在每行结束,除非你手动挑选他们。您可能需要调整puzzle[][](使用MAXCOLS +/- n或其他类似的)以使其为您工作。
for(c=0; c<MAXROWS; ++c){
fgets(puzzle[rows], sizeof puzzle[rows], infile);
}
在循环结束时,puzzle[x][y]
应该是来自输入文件的2d字符数组。