To count number of words in a string.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include "stdafx.h"

#include <iostream>
#include <string>
#include <algorithm>
int main(){
	int m = 0;
	std::cout << "Enter a string to find the Number of words!";
		std::string userString;
		std::cin >> userString;
		std::transform(userString.begin(), userString.end(), userString.begin(), tolower);
		for (int n = 0; n < userString.length(); n++){

			if (userString[n] == ' '){
				m = m + 1;
			}
		}

			std::cout << m;
			
		}

Always displays the same number (0)
Last edited on
Line 10 will stop when it hits a whitespace character, so you can never have a space in userString. Try using std::getline() to read an entire line instead.
I've found two errors in your program. First is in line 7. You declare m to be 0, whereas it should be initially declared as 1, because in your for loop you count spaces, and there's always n-1 amount of spaces in a sentence of n words. Also, there's an error on line 10. You use std::cin>>userString; to get input. You should use getline: std::getline(std::cin, userString)
Topic archived. No new replies allowed.