繁体   English   中英

计算一行文本中有多少个单词? (使用C编程语言)

[英]Count how many words in a line of text? (in C Programming Language)

问题:此代码示例出了什么问题,缺少了什么?

当前不正确的输出是:

“”中有0个单词


代码说明:编写一个程序,该程序读取一行文本,并打印出该行文本中的单词数。 一个单词包含字母数字字符。 提示:使用fgets()函数。

样品运行:

输入:从这里到永恒输出: 4

输入:从此处开始并旋转180度输出: 6

代码段: https : //onlinegdb.com/H1rBwB83V

#include <stdio.h>
#include <ctype.h>
#include <stdbool.h>
#include <string.h>

#define MAXLEN 100

int countWords(char str[])
{
    int i=0;
    int count = 0;
    bool flag = false;

    while (str[i] != '\0')
    {
        if (isalnum(str[i]))
        {
            if (!flag)
            {
                count++;
                flag = true;
            }
        }
        else
            flag = false;

        i++;
    }

    return count;
}

int main(int argc, char **argv) {
    char str[MAXLEN];
    int count;

    while (fgets(str, sizeof(str), stdin) != NULL)
    {
        str[strlen(str-1)] = '\0'; // the last character is the newline. replace with null
        count = countWords(str);
        printf("There are %d words in \"%s\"\n", count, str);
    }

    return 0;
}

相似的教程: https : //www.sanfoundry.com/c-program-count-words-in-sentence/

您在这里有一个错误:

str[strlen (str - 1)] = '\0';   // the last character is the newline. replace with null

使用指针str - 1会导致未定义的行为,因为它指向原始字符串之外的内存。

您实际上打算这样做: strlen(str) - 1 (注意-1已移到括号之外)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM