C 使用txtfile将值输入指针数组
我试图从一个txt文件中获取输入数据到指针数组中。然后将数组显示(打印)为整数的正方形二维数组。下面是TST文件。第一个数字9是设置2d数组大小的N(即nxn)。我可以使用fgetc获取这个值,并将其设置为int值N。接下来,我想在文本文件中获取9x9array,并将这些值放入指针数组,这就是我遇到的问题。任何关于我可以采取的方法的建议C 使用txtfile将值输入指针数组,c,arrays,pointers,conways-game-of-life,C,Arrays,Pointers,Conways Game Of Life,我试图从一个txt文件中获取输入数据到指针数组中。然后将数组显示(打印)为整数的正方形二维数组。下面是TST文件。第一个数字9是设置2d数组大小的N(即nxn)。我可以使用fgetc获取这个值,并将其设置为int值N。接下来,我想在文本文件中获取9x9array,并将这些值放入指针数组,这就是我遇到的问题。任何关于我可以采取的方法的建议 9 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
9
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 1 1 1 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]){
int **A;
FILE *file;
char ch;
int i;
int j;
int N;
int t;
if ( argc != 2 ) /* argc should be 1 for correct execution */
{
printf( "you need to input one argument\n");
}
else {
file = fopen(argv[1], "r"); //opens file name
if(file == 0)
printf("File couldnt me opened\n");
else {
if((ch=fgetc(file))!=1){
N = ch - '0' ;
}
A = malloc(N * sizeof(int *));
for (i = 0; i < N; i++)
A[i] = malloc(N * sizeof(int));
while((ch=fgetc(file)) != EOF){
i=4;
//for (i=1;i<N;i++)
// for (j=1;j<N;j++)
if(i<N)
A[i][i]= ch2 - '0' ;
}
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++)
printf("%d ", A[i][j]);
printf("\n");
}
fclose( file );
}
}
}
9
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 1 1 1 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
#包括
#包括
int main(int argc,char*argv[]){
国际**A;
文件*文件;
char ch;
int i;
int j;
int N;
int t;
如果(argc!=2)/*argc应为1以正确执行*/
{
printf(“您需要输入一个参数\n”);
}
否则{
file=fopen(argv[1],“r”);//打开文件名
如果(文件==0)
printf(“无法打开文件\n”);
否则{
如果((ch=fgetc(文件))!=1){
N=ch-‘0’;
}
A=malloc(N*sizeof(int*);
对于(i=0;i
读取N
if((ch=fgetc(file))!=1){
N = ch - '0' ;
}
如果文件的第一个字符不是其中一个数字,这将给您错误的N
。此外,如果N
大于9
,您将停止使用错误的值。将其更改为
if ( fscanf(file, "%d", &N) != 1 ){
// Problem.
// Do something about it.
}
用于读取矩阵数据的行根本没有意义
while((ch=fgetc(file)) != EOF){
i=4; // Why is i set to 4 here?
if(i<N) // This will always be true when N >= 4
A[i][i]= ch2 - '0' ;
for (j = 0; j < N; j++)
{
if ( fscanf(file, "%d", &A[i][j]) != 1 )
{
// Problem.
// Do something about it.
}
}