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.
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 )
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++;
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;