c++ - Figuring out why Word Counter program output is 0 or 1 -


i need figure out bug program. when type hello world am, should count number of spaces, keep getting 0 or 1. below full program:

    #include "windows.h"     #include <iostream>     #include <cctype>     using namespace std;      //global declarations.      //function prototypes.     void pause();     void numwords(string&);     int numwords(char []);      int main()     {         string userval;         numwords(userval);         char *constr= new char[userval.length()];         strcpy(constr, userval.c_str()); //string converted c-string.         int fin= numwords(constr);         cout<< "the number of words in sentence "<< fin<< "."<< endl;         delete[] constr;         constr= 0;          pause();         return 0; } /***************************************functions**********************************************************************/ /*1st function pause program.*/ void pause() {     cin.sync();     cin.ignore(); }  /*2nd function ask user input. op*/ void numwords(string &len) {     cout << "please enter sentence , tell how many words has: " << endl;     cin >> len; }  /*3rd function count number of total spaces in sentence.*/ int numwords(char usstr[]) {     int wrdcount= 0,         chrcount= 0,         index= 0;     while(usstr[index]!= '\0')     {         if(isspace(usstr[index]))         {             if(chrcount)             {                 wrdcount++;                 chrcount= 0;             }         }         else             chrcount++;         index++;      }     if(chrcount)         wrdcount++;     return wrdcount; } 

can please explain why doesn't count spaces, or if need loop mechanism make work? thank you.

corykramer's suggestion correct. cin stop after first whitespace. if want read whole line, use getline. i've made changes code show renamed function use sentence user. also, don't have convert c-style string work, string works fine.

//function prototypes. void pause(); void getsentence(string&); int numwords(string&);  int main() {     string userval;     getsentence(userval);      int fin = numwords(userval);     cout << "the number of words in sentence " << fin << "." << endl;      pause();     return 0; }  void getsentence(string &len) {     cout << "please enter sentence , tell how many words has: " << endl;     getline(cin, len); }  int numwords(string& usstr) {     int wrdcount = 0,         chrcount = 0,         index = 0;     while(index < usstr.length())     {         ...     }     if(chrcount)         wrdcount++;     return wrdcount; } 

you want #include <string>


Comments

Popular posts from this blog

php - Zend Framework / Skeleton-Application / Composer install issue -

c# - Better 64-bit byte array hash -

python - PyCharm Type error Message -