我有以下代码

int * counter(const char *filename, bool bytes_flag, bool words_flag, bool lines_flag){
    int * counts = malloc(sizeof(int) * 3);
    int line_count = 0;
    int word_count = 0;
    int byte_count = 0;
    size_t line_size = LINE_MAX;
    FILE * file_stream;
    char * line_buffer;

    printf("%d %d %d\n", line_count, word_count, byte_count);

    file_stream = fopen(filename, "r");

    if (file_stream == NULL) {
        printf("File count not be opened.\n");
    }
    else{
        line_buffer = (char *)malloc(line_size);
        while (getline(&line_buffer, &line_size, file_stream) != EOF){

            if (lines_flag){line_count++;}

            for ( int i = -1; line_buffer[i] != '\n'; i++){
                byte_count++;
                if (isspace(line_buffer[i]) && !isspace(line_buffer[i-1])){
                    word_count++;
                }
            }
            //byte_count++;//Count last \n character
        }
        fclose(file_stream);
        
        printf("\n");
        printf("%d\n", line_count);
        printf("%d\n", word_count);
        printf("%d\n", byte_count);
        printf("\n");

        counts[0] = line_count;
        counts[1] = word_count;
        counts[2] = byte_count;
    }
    return counts;
}

我正在输入以下文件

The Project Gutenberg eBook of The Art of War
    
This ebook is for the use of anyone anywhere in the United States and

我的输出几乎就是我想要的,但字数1太高了.发生这种情况是因为文本文件第2行上的空行.

./ccwc.o -l small.txt
0 0 0

3
24
127

我如何才能提高?

if (isspace(line_buffer[i]) && !isspace(line_buffer[i-1])){
    word_count++;
}

才能抓住这个边缘 case ?

推荐答案

To count the number of words, count the transitions from white-space to non-white-space.
Using a separate variable to record the prior character simplifies edge cases.

is...()个函数需要unsigned char值或EOF.

注意:fgets()可能会返回一个不带'\n'的缓冲区.

        unsigned char *s = (unsigned char *) line_buffer;
        unsigned char prior = ' ';
        while (*s != '\n' && *s) {
          byte_count++;
          if (isspace(prior) && !isspace(*s)) {
            word_count++;
          }
          prior = *s;
          s++;
        }

C++相关问答推荐

ARM上的Modulo Sim Aarch 64(NEON)

位屏蔽对于无符号转换是强制的吗?

括号中的堆栈实现错误问题

C编译器是否遵循restrict的正式定义?

在没有动态内存分配的情况下,用C语言最快地将各种数组复制到单个较大的数组中

C是否用0填充多维数组的其余部分?

C++中矢量类型定义和数据保护的高效解决方案

Linux不想运行编译后的文件

在句子中转换单词的问题

MacOS下C++的无阻塞键盘阅读

为什么realloc函数在此代码中修改变量?

Fprintf正在写入多个 struct 成员,并且数据过剩

c程序,让用户输入两类数字,并给出输出用户输入多少个数字

STM32 FATFS用户手册(Um1721)中的代码正确吗?

unions 的原子成员是个好主意吗?

C中的char**v*char[]

程序如何解释变量中的值

将指针的地址加载到寄存器内联拇指组件中

如何转义包含指令中的字符?

C 预处理器中的标记分隔符列表