c - fgets + 动态 malloc/realloc,使用 .txt 作为标准输入

标签 c dynamic malloc realloc

我正在尝试读取文件的行。 txt,但不知道每行的大小...首先我使用了 getline 指令(并且工作正常),但我的老师不允许我使用该指令,他说我只能将 fgets 语句与 malloc 和 realloc 一起使用。 ..

这是一个输入示例,具有可变的行大小:

[9.3,1.2,87.9]
[1.0,1.0]
[0.0,0.0,1.0]

如图所示,每行定义一个不同的 vector ,没有大小限制

有人可以帮我实现这个方法吗?

非常感谢。

注意:我忘了提及,要编译程序,我使用以下命令:

g++ -Wall-Wextra-Werror-pedantic main.c-o metbasicos.c metintermedios.c eda.exe

./eda.exe <eda.txt

最佳答案

我会说做类似的事情

    while(fgets(buf, LEN, stdin)){
            z = strtok(buf, ",");
            *(*(matrix + i)) = atof(z);
            for(j = 1; j < col; ++j){
                    z = strtok(NULL, ",");
                    *(*(matrix + i) + j) = atof(z);
            }
            ++i;
    }

您需要注意的唯一额外事情是确保去掉第一个和最后一个元素的括号。

当然,如果你不知道最终数组的大小,你可能需要这样的东西:

    struct data_t {
            int nval;               /* current number of values in array */
            int max;                /* allocated number of vlaues */
            char **words;           /* the data array */
    };

    enum {INIT = 1, GROW = 2};

    ...
    while (fgets(buf, LEN, stdin)) {
            if (data->words == NULL)
                    data->words = malloc(sizeof(char *));
            else if (data->nval > data->max) {
                    data->words = realloc(data->words, GROW * data->max *sizeof(char *));
                    data->max = GROW * data->max;
            }
            z = strtok(buf, "\n");
            *(data->words + i) = malloc(sizeof(char) * (strlen(z) + 1));
            strcpy(*(data->words + i), z);
            i++;
            data->nval++;           
    }
    data->nval--;

如果您将这两个 while 循环合并为一个循环,那么您应该已准备就绪。第一个读取 float ,第二个适合动态动态分配空间。

关于c - fgets + 动态 malloc/realloc,使用 .txt 作为标准输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19479598/

相关文章:

c++ - malloc 分配的内存可以使用多少时间?

c - C 中 malloc() 的替代方法是什么?

c - 我正在寻找一种高效的 C 对象序列化机制

c - 最大子数组的特殊情况

c - 在 Windows 中为 C 安装编译器?

c - 通缉 : Very Fast Linked Lists in C

c - 在其他字符数组中替换字符数组

javascript - 如何在动态创建的输入上使用 getElementById?

c++ - 高频套接字通信

jquery - ASP.Net/AJAX - 使用 c# 在 asp.net 中动态加载用户控件后,事件不会触发