gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 18:44:58 26 4
gpt4 key购买 nike

问题:这个代码示例有什么问题,缺少什么?

当前不正确的输出是:

“”中有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已移到括号之外)

关于计算一行文本中有多少个单词? (C 编程语言),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56104825/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com