我想将 txt 中的元素扫描到数组中。 txt 没有我将有多少行或列,它只包含一个坐标和数组的元素。它看起来像这样:
2,3
2,1
3,0
-
我怎样才能将这些数字放入一个数组中,以便array[0][0]
将2
and array[1][0]
将3
etc...
我也想让这个与其他输入一起工作。
到目前为止我的代码:
这 ??是因为如果我什至不知道每个输入 txt 将有多少行或列,我不知道应该如何声明这些。
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE* in = fopen("in.txt", "r");
int x, y;
int array[??][??];
if (in == NULL) {
printf("Can't open in.txt");
fclose(in);
return 1;
}
if (fscanf(in, "%d,%d\n", &x, &y) != 2) {
printf("Cant read file.");
return 2;
}
for (int i = 0; i < ??; i++) {
for (int j = 0; j < ??; j++)
fscanf(in, "%d", &array[i][j]);
}
return 0;
}
您想读取值对列表吗?听起来您需要有一个(可能很长)两个数字组的数组。我可以建议建立一个结构来保存这些值,而不是记住 X 是第一个,Y 是第二个。像这样的东西应该有效:
int main()
{
FILE* in = fopen("lis.csv", "r");
int count=0;
int error=0;
int x, y;
typedef struct {
int x;
int y;
} COORD;
COORD array[999]={0};
if (in == NULL) {
printf("Can't open in.txt");
fclose(in);
return 1;
}
while(!feof(in))
{
if (fscanf(in, "%d,%d\n", &x, &y) != 2) {
printf("Cant read file.");
error=1;
break;
}
array[count].x=x;
array[count].y=y;
count++;
}
return error;
}
我没有为错误条件添加任何明亮的内容,如果您在读入这些值后对它们进行一些处理,但您明白了,这会有所帮助。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)