我有一个包含以下文字的文件:
Theendsherethiswillnotjaksdjlasdfjkl;asdjfklasdjfkl;asdfjl;
these
are
the
下面是我的代码:
int i = 0;
bool duplicateFound = false;
while(fgets(line,12,fp)){
for (int j = 0; j < i; j++){
if (strcmp(wordList[j], line) == 0){
duplicateFound = true;
printf("Duplicate Found on Line %d : %s\n", j, wordList[j]);
}
}
if (duplicateFound == false){
strcpy(wordList[i], line);
printf("%s", wordList[i]);
}
i++;*/
printf("%s", line);
}
我正在使用 line 来保存每个单词,以便稍后检查数组中的重复项。 我想要它,以便该函数每行最多只读取 12 个字符,但它会输出以下输出。
实际输出:
Theendsherethiswillnotjaksdjlasdfjkl;asdjfklasdjfkl;asdfjl;
these
are
the
预期输出:
Theendsheret
these
are
the
最佳答案
您真的应该只调用 fgets 然后执行 line[12] = '\0'
,但这并不能干净地处理长行的输入。一种选择是如果 fgets 返回部分行(例如,如果 strchr(line, '\n')
返回 NULL)则简单地中止。
如果你想处理长行,你可以用 getchar 丢弃数据,直到你看到一个换行符。假设您不想将换行符视为 12 个字符之一,您可以执行以下操作:
#include <stdio.h>
#include <string.h>
int
main(void)
{
char line[13];
while( fgets(line, 13, stdin) ) {
char *c = strchr(line, '\n');
int ch;
if( c == NULL ) while( (ch = getchar()) != EOF ) {
if( ch == '\n' ) {
break;
}
} else {
*c = '\0';
}
if( printf("%s\n", line) < 0 ) {
break;
}
}
return ferror(stdout) || ferror(stdin) || fclose(stdout) || fclose(stdin);
}
关于c - 如何使用 fgets() 函数使其每行只读取 12 个字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58479076/