查找长度超过 5 的行数

find number of lines with length more than 5

假设我有一个文件

a
ab
abc
abcd
abcde
abcdef
abcdefg
abcdefgh
abcdefgh
abcdefg
abcdef
abcde
abcd
abc
ab
a

我需要找到带有 length >= 5 的行。 这是代码

int cOriginal(char *fileName)
{
    FILE *file = fopen(fileName, "r");
    char line[256];
    int numberOfStrings = 0;
    while(fgets(line, sizeof(line), file))
    {
        if (strlen(line) >= sizeCap)
        {
            numberOfStrings++;
        }
    }
    fclose(file);
    return numberOfStrings;
}

其中sizeCap是一个常量,定义为

const int sizeCap = 5;

我的main()函数

int main()
{
    char filename[] = "file.txt";
    int cnt3 = cOriginal(filename); // th
    printf("Using function3: %d", cnt3);
    return 0;
}

问题是它 returns 10 而不是 8。我不明白为什么。

我身边没有 IDE 所以我必须使用 g++ 和命令行来编译它所以我不能调试它(或者至少我不知道如何调试)。

有什么问题?

这是因为fgets() reads and stores the trailing newline \n. This \n gets counted as one element while calculating strlen().

你需要在接受输入后去掉那个 \n

  • 手动方式

    1. 勾选 strlen().
    2. 检查 n-1\n 的字节,替换为 [=19=]
    3. 计算最终(实际)strlen
  • 使用库函数

使用strchr()

  1. 您需要使用 strchr() 找出尾随 \n
  2. 如果找到,请使用重新调整的指针将 \n 替换为 [=19=]
  3. 此外,您可以通过从原始输入字符串中减去 returned 指针来获得新的字符串长度。

    示例代码:

    int length = 0;
    char*nl=strchr(line,'\n'); 
    if (nl) 
    {
        *nl='[=10=]';
        length =  nl - line;
    }
    else
        length = strlen(line);
    

使用strtok()

  1. 看看 strtok()man page。读取输入后,您可以使用 \n 作为分隔符 解析 字符串。
  2. 计算 returned 标记的 strlen(),如果它不为 NULL。

一些建议:

  1. 始终检查 fopen() 的 return 值是否为 NULL 以确保成功。
  2. main()的推荐签名是int main(void)