将文本文件读入二维数组 [英] Reading a text file into 2d array
问题描述
我有一个文本文件,在行和列中只有随机字母.我要做的只是创建一个2d数组,以使其为puzzle[i][j]
,如果我放置printf("%c", puzzle[5][4]);
,它将只是给我第4行和第3列字符(因为它从数组中的0开始).到目前为止,这是我的代码.
I have a text file with just random letters in rows and columns. All I would like to do is make a 2d array so that it's puzzle[i][j]
where if I put printf("%c", puzzle[5][4]);
it would simply give me the 4th row and 3rd columns character (since it starts at 0 in an array). Here is my code so far.
#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 %s\n",&puzzle[i]][j]);
//puzzle[i][j]=words;
// printf("%c ", puzzle[i][j]);
}
printf("\n");
}
}
末尾的注释区域(仅是开始部分)用于在编译器中简单地打印出文本文件.我想将其设置为二维数组.
The commented area at the end (just the starting part) works to simply print out the text file in the compiler. I would like to get it to be in a 2d array though.
for(colcount=0;colcount<col;colcount++){...}
推荐答案
我会做类似的事情(我并没有使用所有确切的变量名,但是您知道了):
I would do something like this (I didn't use all of your exact variable names but you get the idea):
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("%s\n", puzzle[row]); to print an entire row */
puzzle[rows][cols] = '\0';
++rows;
}
短得多的版本将在每行的末尾包含换行符和NULL字符,除非您手动将其摘掉.您可能需要调整Puzzle [] [](使用MAXCOLS +/- n或类似的方法)以使其适合您.
much shorter version will have newline and NULL chars at the end of each row unless you manually pick them off. You may have to tweak puzzle[][] (use MAXCOLS +/- n or some such) to make it work for you.
for(c=0; c<MAXROWS; ++c){
fgets(puzzle[rows], sizeof puzzle[rows], infile);
}
在循环结束时,puzzle[x][y]
应该是来自输入文件的2d字符数组.希望有帮助.
At the end of the loop, puzzle[x][y]
should be a 2d array of chars from your input file. Hope that helps.
这篇关于将文本文件读入二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!