【问题标题】:How to repeatedly append text to a string in C?如何重复将文本附加到C中的字符串?
【发布时间】:2015-05-05 03:08:11
【问题描述】:

我正在尝试将文件中的一行重复附加到名为行的字符串中。当我尝试打印这些行时,我的代码运行良好,但由于我必须解析信息,所以我需要存储它。

int main(int argc, char *argv[])
{
    // Check for arguments and file pointer omitted
    FILE *f = fopen(argv[1], "r");
    char *times;
    int i = 0;

    for (i = 0; i < 2000; i++)
    {
        char line[80];
        if (fgets(line, 80, f) == NULL)
            break;

        //I want every line with the text "</time> to be added to string times
        if(strstr(line, "</time>"))
        {
            times = strcat(times, line);  //This line is my problem
        }
    }

    printf(times);

    fclose(f);
    return 0;
}

【问题讨论】:

  • 您阅读过strcat 的文档吗? “目标字符串必须有足够的空间存放结果”
  • 而且也必须被nul 终止。

标签: c append repeat strcat


【解决方案1】:

您的代码不起作用,因为您需要为字符串分配空间。您将items 声明为char 指针,但您没有使其指向有效内存,然后strcat() 尝试写入它导致未定义的行为。

试试这个

char items[1024];

 items[0] = '\0';

items[0] = '\0'; 是因为strcat() 将在第一个字符串中搜索'\0' 字节并将第二个字符串附加到第二个字符串的末尾。

您应该注意,如果要连接在一起的字符串太长而无法容纳items,那么问题将会再次发生。

在这种情况下,您要么需要使用malloc()/realloc() 动态分配空间,要么计算结果字符串的总长度,然后为其分配足够的空间。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-04
    • 1970-01-01
    • 2023-01-11
    • 2014-02-25
    • 1970-01-01
    • 1970-01-01
    • 2018-12-17
    • 2010-09-09
    相关资源
    最近更新 更多