Okay from my understanding of your dilemma, you want the user to input more than one space between words and then count the words after you have entered them.
There are a number of ways to do this. The quick and dirty way of doing so is arguably the following:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
#include <iostream>
#include <string>
using namespace std;
int main()
{
string inputstring;
int count(0);
while(cin.get() != '\n'){
cin >> inputstring;
count++;
}
cout << "The string \""<<inputstring<<"\" has "<< count <<" words"<<endl;
cin.get();
cin.ignore();
return 0;
}
|
This works because
cin skips whitespace unless specified by either using a manipulator such as
noskipws or use of
cin.get() which reads every character. However, the only problem with the above is that it skips over the whitespace - which is not necessarily a good thing depending on what you want to do.
So, with a little modification to your code:
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
|
#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 << "The string \""<< inputstring <<"\" has "<<countWord(inputstring)<<" words"<<endl;
cin.get();
cin.ignore();
return 0;
}
int countWord(string word)
{
int words(0);
for (int i = 0; i<word.length(); i++)
{
if ((!isspace(word[i]))&&(isspace(word[i+1]))||(word[i+1] == '\0'))
{
words++;
}
}
return words;
}
|
The above works as it parses the entire string stored from cin up to the newline character (when "Enter is pressed") - which was what you were doing. However, you desire to find contiguous data between spaces. That is what the above code does. But, what happens when there is no space at the end of the stream entered in
cin? Without the inclusion of
in the
if statement in
countWords means that data between that space and the
null character that terminates every string, would be completely neglected and your answer would be off by one.
In coding as in Math, Engineering and Physics - always test upper, lower and middle boundary conditions as in the above. Cheers! :)