gpt4 book ai didi

c 如何编写一个程序来计算句子中有多少个单词而不使用字符串

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

所以我正在尝试编写这个程序,但我不能使用字符串,而必须使用 getchar 函数。这是我到目前为止所拥有的,但它不起作用,但它可以编译。当我运行它时,它不会返回正确数量的单词。我也尝试过输入单词 += 1 但这也没有帮助。

#include <stdio.h>



int main()
{
char ch;
int words = 1 ;

printf("Enter a sentence ended by a '.', a '?' or a '!': ");
ch = getchar();
while (getchar() !='\n');
{

if (ch == ' ')
words++;

}
printf("Total number of words:%d\n", words);


return 0;
}

最佳答案

假设句子写得正确,一个简单的方法是计算空格数并加 1:

int i = 0, words = 1;

//loop through the string (stop at the null terminating character)
while (sentence[i] != '\0') {
if(sentence[i] == ' ') {words++;}
i++;
}

关于c 如何编写一个程序来计算句子中有多少个单词而不使用字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35617125/

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