【发布时间】: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] = "";
【问题讨论】:
-
在再次使用
fgets()之前,您不必“清空”数组。您应该提供minimal reproducible example 和示例输入。