Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
163 views
in Technique[技术] by (71.8m points)

C++ phrase counter with getche() function

#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 != '
' )
 {
      ch = getche();
      if ( ch !=' ' )
      {
           chcount++;
           count++;          
      }
      else if (count > 2)
           {
                    wdcount++;
                    count=0;
           }
  }


  cout<<"
Count of words is: "<<wdcount+1<<"
Count of charcters is: "<<chcount-1<<"
";

system("pause");
return 0;}

this code counts the words with size greater than two characters and the number of all characters (ignore spaces) in a phrase typed in by the user. The question is why the word counter initial value is considered +1 and character counter initial value considered -1 (as you can see the cout wdcount+1 and chcount-1)?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

After some tries I finally got the correct answer I liked to post it to help anyone interested .. thanks all for your help

#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 != '
' )
 {

      if ( ch !=' ' )
      {
           chcount++;
           count++;      
      }
      else if (count > 2)
           {
                    wdcount++;
                    count=0;             
           }
   ch = getche();
  }

  if (count >2)  //validate that last word is counted
  wdcount++;

  cout<<"
Count of words is: "<<wdcount<<"
Count of charcters is: "<<chcount<<"
";

 system("pause");
 return 0;

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...