Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/59.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
c如何编写一个程序,在不使用字符串的情况下计算句子中的单词数_C - Fatal编程技术网

c如何编写一个程序,在不使用字符串的情况下计算句子中的单词数

c如何编写一个程序,在不使用字符串的情况下计算句子中的单词数,c,C,所以我试图写这个程序,但我不能使用字符串,必须使用getchar函数。这是我到目前为止所拥有的,但它不起作用,但它可以编译。当我运行它时,它不会返回正确的字数。我也试过把单词+=1放进去,但也没用 #include <stdio.h> int main() { char ch; int words = 1 ; printf("Enter a sentence ended by a '.', a '?' or a '!': "); ch = getchar()

所以我试图写这个程序,但我不能使用字符串,必须使用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;
  }
#包括
int main()
{
char ch;
int字=1;
printf(“输入以“.”、“?”或“!”结尾的句子:”;
ch=getchar();
而(getchar()!='\n');
{
如果(ch='')
words++;
}
printf(“总字数:%d\n”,字数);
返回0;
}

ch=getchar();需要在while循环中。否则,ch永远不会更新。另外,不要忘记if语句的括号。并更改getchar()!='\n'在while循环到ch!='\n'

假设句子写得正确,一个简单的方法是计算空格数并加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++;
}
改变

注意分号的删除。使用分号时,循环不会执行您在循环括号中给出的指令

如果希望下次轻松解决所有这些问题,请使用编译器的标志并启用完整警告


如果您使用的是
gcc
,请使用标志
-Wall
-Wextra
<代码>-墙会给你额外的警告,包括你愚蠢的错误<代码>-Wextra将使您收到的所有警告都出错,确保您注意这些警告。

嘿,伙计,我试过了,但它所做的只是在原始打印后再打印一行,答案仍然是错误的。谢谢,读我的新答案。我在你的代码中发现了另外两个错误。在我尝试了之后,一旦你在句子中输入,按enter键只会创建一个新行。你看到其他关闭的吗?谢谢你的帮助。你能发布我建议的更新代码和输入示例吗?此外,删除while条件
while(任何内容)后的分号
是一个没有主体的循环,因为
。这解决了我的问题,非常感谢。
while (getchar() !='\n'); 
while (getchar() !='\n')