Word Parser not working

I am trying to create a word parser that will split a sentence into it's individual words so I can then interpret meaningful words into commands. This is what I have so far.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#ifndef CCOMMANDPARSER_H
#define CCOMMANDPARSER_H
#include <iostream>

class Ccommandparser
{
	public:
		void getCommand();
		void findWords();
	private:
		const static unsigned int LIMIT = 10;
		unsigned int startPos, endPos, wordsFound;
		std::string sentence;
		std::string word[LIMIT];

};

#endif 


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 "ccommandparser.h"
#include <iostream>

void Ccommandparser::getCommand()
{
	std::cout << "Please enter your decision." << std::endl;
	std::cin >> sentence;
	findWords();
}

void Ccommandparser::findWords()
{
	startPos = 0;
	endPos = 0;
	wordsFound = 0;
	
	for ( unsigned int x = 0; x < sentence.length(); x++ )
	{
		if ( sentence[x] == ' ' )
		{
			endPos = x;
			for ( unsigned int y = startPos; y < endPos; y++ )
			{
				word[wordsFound] = word[wordsFound] + sentence[y];
			}
			wordsFound++;
			startPos = endPos;
		}
	}
	std::cout << sentence;
}
So far, it is not correctly storing the found word in the array of found words called *word*
Although you didn't really state what the problem is, I took the liberty of finding it for you. The problem arises from the way you are reading the sentence. The istream '>>' operator stops reading input when it encounters a white space character (space, newline, tab, etc); this means that if you had a long sentence as input, line 7 will only read the first word of the sentence.

Now with this in mind, do you see a way of using this behaviour to your advantage rather than running to the getline function?

To address you second post, the reason it is not storing the word (remember it only reads first word before a space character) is because of your if statement on line 19. Since the word it reads does not contain a white space character, the word is never stored in the array
Last edited on
Topic archived. No new replies allowed.