在C语言中,我如何打印出一个字符数组,然后将其清空?

时间:2019-02-24 14:42:36

标签: c arrays char character

我正在尝试每行读取一个文件行,并检查是否有任何标签以“ 标签:”的形式写入。它检查分号的存在,几乎只将分号之前的字符附加到字符数组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] = "";

2 个答案:

答案 0 :(得分:3)

这没有达到您的期望:

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,但是正在创建名为{{ 1}}。该变量立即超出范围,因此无效。然后,您将继续为每个标签附加到temp,最后是temp

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

temp

还要注意,我们 else if (line[i] == ':') { printf("Scanned label %s\n", temp); temp[0] = '\0'; break; } 超出了内循环,因此我们可以读取下一行。

答案 1 :(得分:1)

真的不需要“清空”临时数组。

  

关于清空字符数组,我做的对吗?只需简单地:char temp[200] = "";

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

其他备注:

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