我正在尝试读取文件的行。 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/