【问题标题】:In C, how do I print out a character array then empty it after?在 C 中,如何打印出一个字符数组然后将其清空?
【发布时间】:2026-01-25 18:50:01
【问题描述】:

我正在尝试每行读取一个文件行并检查是否有任何标签,这些标签以“label:”的形式写入。它检查分号的存在并且几乎只是将分号之前的字符附加到字符数组temp 中。然后,清空temp 并使用 fgets 函数读取下一行。

这是我目前写的代码:

char temp[200] = "";

    while(fgets(line, len, fp) != NULL)
    {
        for(int i = 0; i < strlen(line); i++)
        {
            if (line[i] == ' ') continue;
            else if(line[i] != ' ' && line[i] != ':')
            {
                append(temp, line[i]);
                continue;
            }
            else if (line[i] == ':')
            {
                printf("Scanned label %s\n", temp);
                char temp[200] = "";
            }
        }
    }

append 是一个特殊函数,用于将单个字符附加到字符数组temp

void append (char* str, char ch)
{
    int len = strlen(str);
    str[len] = ch;
    str[len+1] = '\0';
}

在文本文件的四行中,每一行都有一个标签。这是输入文件的示例:

L1: this is a sentence
L2: this is another sentence
L3: this is another sentence
L4: this is the last sentence

我设法得到了输出

Scanned label
Scanned label
Scanned label
Scanned label

但如您所见,我无法打印出字符数组temp 的内容。所以,我的问题是,如果有什么我可以解决这个问题,或者我的代码是否存在任何逻辑缺陷?

至于清空字符数组,我做对了吗?只需:

char temp[200] = "";

【问题讨论】:

标签: c arrays char character


【解决方案1】:

这不是你所期望的:

else if( ( line[i] != ' ' || line[i] == ':') && (line[i] == '\0'))

仅当line[i] 是终止空字节时,此条件才会成立,因此您唯一要附加到字符串的就是那个。如果你得到一个非空格或非:,你想追加。你这样做:

else if( ( line[i] != ' ' && line[i] != ':'))

然后是这部分:

        else if (line[i] == ':')
        {
            printf("Scanned label %s\n", temp);
            char temp[200] = "";
        }

读取char temp[200] = ""; 的行不是清除块顶部定义的temp,而是创建一个名为temp变量。此变量立即超出范围,因此没有效果。然后,您将继续为每个标签附加到 temp,以 "L1L2L3L4" 结尾。

要使temp 为空字符串,只需将第一个元素设置为0:

        else if (line[i] == ':')
        {
            printf("Scanned label %s\n", temp);
            temp[0] = '\0';
            break;
        }

还要注意,我们 break 退出了内部循环,因此我们可以阅读下一行。

【讨论】:

    【解决方案2】:

    确实没有必要“清空”临时数组。

    至于清空字符数组,我做对了吗?只需:char temp[200] = "";

    只需在初始化时使用char temp[200]; 就足够了。 if 语句中的第二个声明是完全错误的。只需将其删除。

    其他说明:

    (line[i] != ' ' || line[i] == ':') 将始终评估为真。您应该检查这种情况。

    【讨论】:

    • 您的回答很有帮助,非常感谢!不敢相信我错过了。不过我有一个问题,既然您说“不需要清空临时数组”,这是否意味着将“\0”附加到字符数组的末尾会截断它并使数组为空?或者那是因为我正在阅读带有 fgets() 函数的新行,就像其他评论所说的那样?
    • 任何以前的 `\0' 都将被忽略或覆盖。
    最近更新 更多