gpt4 book ai didi

c - 逐行读取文本并为每行分配变量

转载 作者:行者123 更新时间:2023-11-30 19:10:07 25 4
gpt4 key购买 nike

我已经完成了让我的 C 程序逐行读取文本。这是最容易的部分,至少在我看来是这样。我现在需要做的是为每行分配变量。例如,文本文件的第一行将等于变量 line1。

或者这个

char line1 = (text from line one)
char line2 = (text from line two)

到目前为止我的代码:

    char line[1000] = ""; 

FILE *ifp;

ifp = fopen("Tree-B.txt", "r");
if (ifp == NULL)
{
printf("Error opening file!\n");
exit(1);
}

while (fscanf(ifp, "%s", line) == 1)
{
printf("%s ", line);
}
printf("\n");
fclose(ifp);

return 0;

我完全不知道该怎么做。

最佳答案

为此,您可以使用指针数组。

char line[1000] = "";  // assume each line has at most 999 chars (1 space for NUL character)
char *lines[1000] = { NULL }; // assume max number of lines is 1000
int idx = 0;
FILE *ifp;

ifp = fopen("q2.cpp", "r");
if (ifp == NULL)
{
printf("Error opening file!\n");
exit(1);
}

while(fgets(line, sizeof(line), ifp) != NULL)
{
lines[idx] = strdup(line);
printf("%s", lines[idx]);
idx++;
}

注释:

  • 此方法使用 POSIX(不是官方 C 标准)的 strdup。但是,您可以输入 publicly available strdup 函数本身。

  • fgetsfscanf 更受青睐,因此我这样更改了它。

  • 1000 limis 是有建议性的 - 您可以/应该将这些常量更改为对程序本身更有意义的值。

关于c - 逐行读取文本并为每行分配变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41864987/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com