Do not count multiple spaces as words

I'm making a program that counts the number of words from a user's input. So far, it works but only if the user inputs one space between words. Otherwise, the program starts counting too many spaces as words.

My 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
#include <iostream>
#include <string>
using namespace std;

int main()
{
	int i;
	int NumSpaces;
	char NextChar;
	string userinput;

	NumSpaces= 1;

	cout << "Enter your string " << endl;
	getline(cin, userinput);

	
	for (i=0; i <int(userinput.length()); i++)
	{
		NextChar = userinput.at(i); 
		if (isspace(userinput[i]))
			NumSpaces++;
	}
	cout << NumSpaces << " words in your string." << endl;
	cin.ignore();
	return 0;
}


How do I fix this?
Last edited on
You can add a nested loop. When the first space is found keep reading until you reach the end of the string or you fine a non-space character.

Or you could create a stringstream which would do much of this on it's own and use operator>> from it to get every space-separated string ( and so count them )
How would I go about coding it so that NumSpaces stops counting after 1 spaces, but continues looking for the next char?
Just check the next character for a space simultaneously and only increment NumSpaces if there isn't one. That way it won't increment if there is a consecutive space.

1
2
if ( (isspace(userinput[i])) && !(isspace(userinput[i + 1])) )
			NumSpaces++;
#include <iostream>
#include <string>
#include <sstream> // added
using namespace std;

int main()
{
int i;
int NumSpaces;
char NextChar;
string userinput;

NumSpaces= 1;

cout << "Enter your string " << endl;
getline(cin, userinput);


for (i=0; i <int(userinput.length()); i++)
{
NextChar = userinput.at(i);
if (isspace(userinput[i]))
NumSpaces++;
}
cout << NumSpaces << " words in your string." << endl;
cout << "Press return to see solution!\n";
cin.ignore();

// This will give you number of words in your string regardless of any whitespace tabs
NumSpaces=0;
istringstream instr(userinput);
while(instr >> userinput) {
NumSpaces++;
}
cout << NumSpaces << " words in your string." << endl;


return 0;

}
Topic archived. No new replies allowed.