【问题标题】:fscanf into a 2d array in Cfscanf 到 C 中的二维数组中
【发布时间】:2018-11-22 18:59:53
【问题描述】:

我想将 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;
}

【问题讨论】:

  • 您说“它只包含一个坐标和元素”,但我在示例输入中没有看到 array[0][0] 的坐标。
  • 不是array[0][1]应该是3array[1][0]是下一个2吗?这对我来说更有意义。
  • 这个问题我不清楚;你为什么读xy?它们实际上是数组边界吗?但之前你说你不知道数组边界。尝试更好地描述这一点会改善问题,并提供您尝试阅读的文件的真实示例。对于您提供的文件,您只需要一个固定宽度 2 的数组,因为每行有 2 个元素

标签: c arrays scanf


【解决方案1】:

您想读取值对列表吗?听起来您将需要一个(可能很长)由两个数字组成的数组。与其记住 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;
}

我没有为错误条件添加任何亮点,如果您在读入这些值后对它们进行一些操作,但您明白了,这会有所帮助。

【讨论】:

  • 我试图帮助 fscanf 和存储数据的位置。如果是我,我会用while(fgets(linein,sizeof(linein), in)) 编写它。只是碰巧在这种情况下,使用 Linux(和 cygwin)上的 GCC,EOF 测试发生在最后一个 fscanf 之后,所以它工作正常。如果 fscanf 没有检测到 EOF,则 fscanf 和 break 的测试将避免存储污染的数据。
【解决方案2】:

您应该使用动态数组分配将未知 txt 文件中的元素扫描到数组中。 对于 C++ 程序员来说,最好的解决方案是std::vector。 但是 C 程序员应该使用替代解决方案。 请阅读这篇文章:(std::vector alternative for C)

【讨论】:

    猜你喜欢
    • 2016-08-15
    • 1970-01-01
    • 2013-11-23
    • 2015-10-18
    • 2013-10-05
    • 1970-01-01
    • 1970-01-01
    • 2020-01-18
    • 2020-08-10
    相关资源
    最近更新 更多