我有一个代码可以读取文本文件,对其中的单词进行标记,然后仅从文本中选择唯一的单词,然后将它们连接起来并使用puts()函数进行打印。 这是完整的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char str_array[100][100];
char output[100];
void concatenate(int index)
{
// compares output with empty string
if (!strcmp(output, ""))
{
strcpy(output, str_array[index]);
}
else //else existing string is contcatenated
{
strcat(output, " "); // add space
strcat(output, str_array[index]);
}
}
void unique_selection(char file[])
{
FILE *F = fopen(file, "r");
char ch; char str[100];
int i=0, j=0;
while ((ch=getc(F)) != EOF)
{
// if space or newline is detected i.e. word is finished
if (ch == ' ' || ch == '\n')
{
//traverse array of strings
for(int x=0; x<j; x++)
{
//if current str is already in array, skip appending
if (!strcmp(str_array[x], str)) goto ELSE;
}
strcpy(str_array[j], str);
j++;
ELSE:
i=0;
memset(str, 0, strlen(str));
}
else //otherwise chars of a word get appended to string array
{
str[i] = ch;
i++;
}
}
for(int k=0; k<j; k++)
{
concatenate(k);
}
puts(output);
fclose(F);
}
int main(void) {
char file[] = "test.txt";
//printf("Output:");
unique_selection(file);
return 0;
}
代码运行正常,但是每次遇到尝试打印输出字符串(使用puts()
或printf("%s")
时,程序都会卡住的问题,与循环时发生的情况类似,我遇到了一个奇怪的问题永远重复着,而且很奇怪,此问题已通过将printf放在函数调用之前得到解决。如果我从函数中删除puts()
,即使在main()
中有或没有printf,代码也能正常运行。
为什么会这样?