c - 将 fscanf 转换为 C 中的二维数组

标签 c arrays scanf

我想将 txt 中的元素扫描到数组中。 txt 没有我将有多少行或列,它只包含一个坐标和数组的元素。它看起来像这样:

2,3
2,1
3,0
-

如何将这些数字放入数组中,以便 array[0][0] 将是 2array[1][0] 将是 3 等等...

我也希望能够与其他输入一起使用。

到目前为止我的代码:

??是因为如果我什至不知道每个输入 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;
}

我没有为错误条件添加任何明亮的内容,如果您在读入这些值后对其进行一些处理,但您明白了,这会有所帮助。

关于c - 将 fscanf 转换为 C 中的二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53436800/

相关文章:

C fscanf 复杂格式

c - 在输出平均数时,程序呈现段错误 11

c - token 之前的预期表达式

c - 当我并发访问 pthread_mutex_t pthread_mutex_lock.c :62: __pthread_mutex_lock: Assertion `mutex->__data.__owner == 0' failed 时出错

C++14自动推导错误: function returns an array

关于在 C 中打印字符串数组的困惑

python - 高效计算 NumPy 数组的成对相等

c++ - WIN32内存问题(debug/release的区别)

c - 在 C 中不使用 fseek 移动文件位置

c - 扫描: "%[^,]s"与 "%[^,],s"