c - 如何使用 fgets() 函数使其每行只读取 12 个字符?

标签 c function fgets

我有一个包含以下文字的文件:

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/

相关文章:

c - 我在 eclipse 中使用 stdin 和 NULL 时遇到问题

c++ - 如何判断传入的数组是一维、二维还是N维数组

php - 只允许字符串中的某些字符

c - 在进入循环之前 fgets() 不断被跳过

function - 从函数、子函数或类型返回多个值?

java - 我可以通过mysql触发器执行mysql之外的任何程序吗?

c - 从 fgets() 输入中删除尾随换行符

c - 数组中的文件指针

java - 如何制作一个自动同步的程序

c - 是否可以使用 .d 文件来编译所有依赖的 c 文件?