Program That Counts Number of Words

Write your question here.
Hello everyone I have another program to do that counts the number of words in an input. My code works for all cases except for one word. Can someone help me with that?
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
41
42
43
44
45
46
// WordCount.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <string>
#include <iostream>
using namespace std;
int CountWord (string line);
int _tmain(int argc, _TCHAR* argv[])
{
	string sentence;
	string line;
	cout<< "Enter your sentence"<<endl;
	getline (cin, line);
	cout<< "Your sentence is" <<" "<< line<<endl;
	cout<< "There are" << " " <<CountWord (line) << " "<<"words"<<endl;
	return 0;
}

int CountWord (string line)
{
	int llength= line.length();
	int words=1;
	for( int size=1; llength>size; size++)
	{
		if (line[size] == ' ' && line[size-1] != ' ') 
			words++;
	}
	while(line.front() == ' ')
	{
	line.erase(0,1);
	llength--;
	}
	while(line.back() == ' ')
	{
		line.erase (llength-1,1);
		llength--;
	}
	if(words==1)
	{
		words--;
	}

	
	return words;
}
If your code works for all cases except when words == 1, what is the purpose of the following?
1
2
3
4
5
if(words==1)
{
    words--;
}
return words;

Your code can never return 1 due to this.
Why not just iterate through the sentence characters, count the spaces, and return (num_spaces+1)?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <string>
#include <algorithm>

unsigned short getNumWords(const std::string& string) {
	return (std::count(string.begin(), string.end(), ' ') + 1);
}

int main(int argc, char* argv[]) {
	std::string string = "This is a sentence!";

	std::cout << "Sentence:\t" << string << std::endl;
	std::cout << "Word count:\t" << getNumWords(string) << std::endl;
	//... 
Last edited on
Why not just iterate through the sentence characters, count the spaces, and return (num_spaces+1)?
How many words does following line contains:
Hello,                           World!



Another solution, using stringstreams:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <string>
#include <sstream>

int countWords(const std::string& line)
{
    std::istringstream str(line);
    std::string dump;
    int count = 0;
    while(str >> dump)
        ++count;
    return count;
}

int main()
{
    std::cout << "Enter line\n";
    std::string line;
    std::getline(std::cin, line);
    std::cout << "Sentence: " << line << '\n' <<
              "Word count: " << countWords(line) << '\n';
}
Enter line
a    quick brown  fox jumps over the lazy    dog
Sentence: a    quick brown  fox jumps over the lazy    dog
Word count: 9
http://ideone.com/Alx3N2
Topic archived. No new replies allowed.