Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

#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

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

1 Answer

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;

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...