[英]Getting 2d char array dimensions and content from a text file C
There are a lot of questions like this in stack, but I could not find one on the specific issue thus I decided to post..堆栈中有很多这样的问题,但我找不到关于特定问题的问题,因此我决定发布..
I get my input from a text file which is always structured like this:我从一个结构如下的文本文件中获取输入:
X Y
A1 A2 AY
A4 A5 ..
AX .. ..
Dimensions of a 2d array on the first line and a 2d array composed of characters with X rows and Y columns.第一行二维数组和由 X 行 Y 列字符组成的二维数组的维度。
Something goes wrong while transitioning from the first row of the text file to the rest.从文本文件的第一行转换到 rest 时出现问题。
My code for the input is the following:我的输入代码如下:
#include<stdio.h>
#include<stdlib.h>
int n,m;
int main(int argc,char **argv){
if(argc!=2){
perror("Error: ");
return EXIT_FAILURE;
}
FILE* txtfile=fopen(argv[1],"r");
if(txtfile<0){
perror("Error: ");
return EXIT_FAILURE;
}
char lab[n][m];
fscanf(txtfile,"%d %d",&n,&m);
for(int i=0; i<n; i++){
for(int j=0; j<m; j++){
fscanf(txtfile," %c",&lab[i][j]);
}
}
An example input is the following:示例输入如下:
3 3
ULD
LUD
LRL
Which produces the result:产生结果:
lab[0][0] = L
lab[0][1] = R
lab[0][2] = L
lab[1][0] = L
lab[1][1] = R
lab[1][2] = L
lab[2][0] = L
lab[2][1] = R
lab[2][2] = L
Which is obviously wrong... If I provide n,m through user input through the terminal or give them a value inside my program (n=3 and m=3 in this case), and remove them from the text file:这显然是错误的......如果我通过终端的用户输入提供 n,m 或在我的程序中给他们一个值(在这种情况下为 n = 3 和 m = 3),并将它们从文本文件中删除:
ULD
LUD
LRL
I then get the correct 2d array:然后我得到正确的二维数组:
lab[0][0] = U
lab[0][1] = L
lab[0][2] = D
lab[1][0] = L
lab[1][1] = U
lab[1][2] = D
lab[2][0] = L
lab[2][1] = R
lab[2][2] = L
I have tried using fseek to move the pointer in the file to the second line after the first is read, but without results.在读取第一行后,我尝试使用 fseek 将文件中的指针移动到第二行,但没有结果。
Any help/explanation is appreciated, I'm still new to C.感谢任何帮助/解释,我还是 C 的新手。
Well, answering my own question, and to learn from my own stupidity... I declared the character array before actually assigning values to n,m resulting in a "broken array".好吧,回答我自己的问题,并从我自己的愚蠢中学习......我在实际将值分配给 n,m 之前声明了字符数组,从而导致“数组损坏”。 I spent half a day thinking it was some convoluted C pointer thing I was missing, but turns out it was just an amateur mistake... Literally figured 5 minutes after posting...
我花了半天的时间认为这是我遗漏的一些令人费解的 C 指针的东西,但事实证明这只是一个业余错误......在发布后 5 分钟字面意思是......
char lab[n][m];
fscanf(txtfile,"%d %d",&n,&m);
Is wrong and should be:是错误的,应该是:
fscanf(txtfile,"%d %d",&n,&m);
char lab[n][m];
I will keep the questiοn undeleted in case anyone else does the same stupid mistake...我会保持这个问题不被删除,以防其他人犯同样的愚蠢错误......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.