我试图每行读取一个文件行并检查是否有任何标签,这些标签以“标签:”的形式编写。它检查分号是否存在,几乎只是将分号前的字符附加到字符数组 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] = "";
最佳答案
这不是您所期望的:
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] = "";
的行不是清除 block 顶部定义的 temp
,而是创建一个名为 temp
的新 变量。这个变量立即超出范围,所以它没有效果。然后,您将继续为每个标签附加 temp
,以 "L1L2L3L4"
结束。
要使 temp
成为空字符串,只需将第一个元素设置为 0:
else if (line[i] == ':')
{
printf("Scanned label %s\n", temp);
temp[0] = '\0';
break;
}
另请注意,我们 break
跳出内部循环,以便我们可以阅读下一行。
关于c - 在 C 中,如何打印出一个字符数组然后清空它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54852997/