fscanf进入C中的2d数组 [英] fscanf into a 2d array in C
问题描述
我想将txt中的元素扫描到数组中. txt没有我要拥有的行数或列数,它仅包含一个坐标和数组的元素.看起来像这样:
I want to scan elements from a txt into an array. The txt doesn't have how many rows or columns I'm going to have, it only contains a coordinate, and the elements of the array. It looks like this:
2,3
2,1
3,0
-
我如何将这些数字放入数组中,以使array[0][0]
将是2
而array[1][0]
将是3
等...
How can i put these numbers into an array so that array[0][0]
will be 2
and array[1][0]
will be 3
etc...
我也想与其他输入一起使用.
I want to make this work with other inputs as well.
到目前为止我的代码:
??在那里是因为我不知道如果我什至不知道每个输入txt会有多少行或列,我该如何声明它们.
The ?? is there because I have no idea how I should declare these if I don't even know how many rows or columns every input txt will have.
#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;
}
推荐答案
您应使用动态数组分配将元素从未知的txt文件扫描到数组中. 对于C ++程序员而言,最佳解决方案是 std :: vector . 但是C程序员应该使用替代解决方案. 请阅读这篇文章:( std :: vector替代C )
You should use dynamic array allocation to scan elements from an unknown txt file into an array. for C++ programmers the best solution is std::vector. but C programmers should use alternative solutions. please read this post: (std::vector alternative for C)
这篇关于fscanf进入C中的2d数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!