c - 为什么在 C 中 strtok() 会分割单词并将单词限制为 7 个字符?

标签 c

我这两天到处找,还是没搞明白。以下是输出的一个小示例:

它应该是“并找到乐趣”:

f

工业

一个

p

休闲

================

长度计数

================

1 9054

2 10102

3 9336

4 5944

5 3311

6 1656

7 1292

================

平均2.86

================

下面是代码:

#include <stdio.h>
#include <stdlib.h>
#include<string.h>

#define DELIM " ,.;:'\"&!? -_\n\t\0"

int process(int *count, char *buffer);
int printOut(int *count);

int main() {
    char *buffer = (char *) calloc(1, 50*sizeof(char*));
    int *count =(int*) calloc(50, 50*sizeof(long));

    while (fgets(buffer, sizeof buffer, stdin)) {
        process(count, buffer);
    }

    printOut(count);
    free(count);
    return 0;
}

int process(int *count, char *buffer) {
    int word_len=0, i;
    char *pch;
    pch = strtok(buffer, DELIM);
    while (pch != NULL) {
        for(i=0; pch[i] != '\0'; i++) {
                word_len++;
        }
        count[word_len]++;
        word_len=0;
        printf("%s\n", pch);
        pch = strtok(NULL, DELIM);
    }
    return 0;
}

int printOut(int *count) {
    int i;
    double num=0;
    double total=0;
    double average=0;
    printf("================\n");
    printf("len  count\n");
    printf("================\n");
    for(i=0;i<50;i++){
        if(count[i]!=0){
            num=count[i]+num;
            total=total+(count[i]*i);
            printf("%d   %d\n",i,count[i]);
        }
    }
    average = total/num;
    printf("================\n");
    printf("average %.2f\n", average);
    printf("================\n");
    return 0;
}

最佳答案

这是错误的:

 char *buffer = (char *) calloc(1, 50*sizeof(char*));

应该是:

 sizeof(char) // or since this is always 1: 'calloc(1, 50)'

但真正的问题在这里:

fgets(buffer, sizeof buffer, stdin);

Sizeof buffer 是 4(或者任何 sizeof 指针),因为它是一个指针,你需要这样做:

fgets(buffer, 50, stdin);

此外,count 的 calloc 调用中的 sizeof(long) 也不是重点,否则您需要 sizeof(int)您可能会分配比您打算分配的更多字节(取决于体系结构)。所以这可以是:

int *count =(int*) calloc(50, sizeof(int));

关于c - 为什么在 C 中 strtok() 会分割单词并将单词限制为 7 个字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15236755/

相关文章:

c - H.264 1080p 编码

c - Xcode 5 在构建过程中不复制静态库文件

c - 通过 TCP-IPv6 连接进行数据传输

c - 主存中的程序元素

c - Printf 在 Ubuntu 中不工作

c - send() 什么时候返回 EWOULDBLOCK?

c - 如何在 C 中重命名/别名函数?

c++ - 使用 PoDoFo 库从 PDF 运算符中的数组 TJ 中提取文本

c - 我在 OSX 上的 gcc 中不断得到 "Segmentation fault: 11",但在 Windows 上工作

c - 如何在输入方面使用循环(C语言)?