@filipe:
What if the user inputs no words, just whitespace? |
Excellent question and also an excellent catch. ;) My code misses that completely - I didn't test the boundary conditions well LOL. That being said, below is the corrected version:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
|
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int countWord(string word);
int main()
{
string inputstring;
cout << "Enter your string: " << endl;
getline(cin, inputstring);
cout << inputstring << endl;
cout << "The string \""<< inputstring <<"\" has "<<countWord(inputstring)<<" words"<<endl;
cin.get();
return 0;
}
int countWord(string word)
{
int words(0);
int spaces(0);
for (int i = 0; i<word.length(); i++)
{
if((!isspace(word[i]))&&(isspace(word[i+1]))||(word[i+1] == '\0'))
{
words++;
}
if(isspace(word[i]))
{
spaces++;
if(spaces == word.length())
{
words = 0;
}
}
}
return words;
}
|
Why the added peice and not:
? Note, it works and gets the problem solved, but does not flow logically with what is going on. Because, as
filipe implies, which I endorse, is that if the user entered only whitespace, it will print 1, which is incorrect. The corrections that I made above ensures that if the string is indeed whitespace, the total words will always be zero. Additionally, the last part of the if statement that I wrote:
was written to ensure that the information between the last space and the null character was picked up. In so doing, you do not need
if you wanted to perform other operations on the substrings.
I hope that answers your question
dznguy or any other questions you may have had. If not, let us know. :)
Thank you
filipe for your guidance on the above.