C++带有getche()函数的短语计数器

C++ phrase counter with getche() function

本文关键字:短语 计数器 函数 带有 getche C++      更新时间:2023-10-16
#include<iostream>
using namespace std;
#include<conio.h>
int main()
{
int chcount = 0, wdcount =0, count = 0;
char ch='a';
cout << "Enter your text : ";
while ( ch != 'r' )
 {
      ch = getche();
      if ( ch !=' ' )
      {
           chcount++;
           count++;          
      }
      else if (count > 2)
           {
                    wdcount++;
                    count=0;
           }
  }

  cout<<"nCount of words is: "<<wdcount+1<<"nCount of charcters is: "<<chcount-1<<"n";
system("pause");
return 0;}

此代码计算大小大于两个字符的单词以及用户键入的短语中的所有字符(忽略空格)的数量。问题是为什么单词计数器初始值被认为是 +1,字符计数器初始值被认为是 -1(如你所看到的 cout wdcount+1 和 chcount-1)?

经过一些尝试,我终于得到了正确的答案,我喜欢发布它来帮助任何感兴趣的人..谢谢大家的帮助

#include<iostream>
using namespace std;
#include<conio.h>
int main()
{

int chcount = 0, wdcount =0, count = 0;
char ch=' ';
cout << "Enter your text : ";
while ( ch != 'r' )
 {
      if ( ch !=' ' )
      {
           chcount++;
           count++;      
      }
      else if (count > 2)
           {
                    wdcount++;
                    count=0;             
           }
   ch = getche();
  }
  if (count >2)  //validate that last word is counted
  wdcount++;
  cout<<"nCount of words is: "<<wdcount<<"nCount of charcters is: "<<chcount<<"n";
 system("pause");
 return 0;
}