输入一行英文句子,统计单次个数

请求解答
int num=0,word=0;
char ch;
printf("请输入一行字符:\n");

while((ch=getchar())!='\n')
{
    if(ch==' ')
    {
        word=0;
    }
    else if(word==0)
    {
        word=1;
        num++;
    }

}

printf("the number of words is = %d ",num);

printf("\n");
system(" pause ");

img


输入时,输入的第一个字符是空格与第一个字符是字母时个数一样 为什么循环判定时第一个字符是字母

img

int num=0,word=0;
char ch;
printf("请输入一行字符:\n");
scanf("%s",&ch);//这个地方用scanf赋值时,为什么少一个呢

img


#include <stdio.h>
#include <stdlib.h>
 
 
int main()
{
   char ch;
   int sum = 0,word = 0;//用word来判断输入的单词是否结束,即当前输入的字符是不是依旧属于一个单词中
 
   while((ch=getchar())!='\n')
   {
       if(ch == ' ')
        word = 0;//表示一个单词输入完成
       else if(word == 0)
       {
           word = 1;//表示当前正在输入单词
           ++sum;
       }
   }
 
   printf("%d",sum);
 
   return 0;
}

其实整个程序不用这么麻烦,直接用while+cin就可以了
核心Code:

string s;
int cnt=0;
while(cin>>s){           //每次输入一个单词,遇到空格就截断。如果全部输入完毕,自动结束while。
    cnt++;
}

如果你运行程序并输入了一行字符串,再按Enter,你会发现显示不出来,此时按下Ctrl+Z在按回车就可以了。提交到网站上也可以这么写,他自动评测就会自动有一个“Ctrl+Z”。