Isolating words in a string

I'm trying to write a translator program but I'm having trouble isolating words in a string. Here's basically how I've been doing it:

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

int main()
{
	string input;
	cout << "What would you like to translate?\n";
	while (true)
	{
		cin >> input;
		// reads each word separated by a space.
		if (input == "example")
		{
			cout << "Translated example ";
		}
		// translates the word depending on what it is.
		else
		{
			cout << "[" << input << "] ";
		}
		// if the word isn't recognized, outputs it in brackets to show it couldn't be translated.
	}
	
	return 0;
}


The translating part worked fine. The problem is that the else is always activated because it's checking to see if the entire string of input is equal to "example" and when its not, it outputs every word untranslated in brackets. So if you typed "example translation" it would output:

Translated example [example] [translation]


So I guess I need to learn how to isolate individual words with getline(). Thanks in advance, and sorry if the example program was a bit confusing. My actual program is much too long to post here.

EDIT: Hm, nevermind. I just compiled the example program and it worked. But it was not working for the actual translator. Anyway I still need to know how to do it with getline for other reasons too difficult to explain.
Last edited on
This code should do it with getline.
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
#include <iostream>
#include <string>
#include <strstream>

using namespace std;

int main()
{
	cout << "What would you like to translate?\n";
	const size_t len = 1000;
	char s[len];
	cin.getline( s, len );

	strstream ss;
	ss << s;
	
	while ( ss.good() )
	{
		string word;
		ss >> word;
		if ( word == "example" )
			cout << "Translated example ";
		else
			cout << "[" << word << "] ";
	}

	return 0;
}

The input string is limited to length 1000. This should behave like your program, but the user can hit enter only once.
Ah, thank you, this should do the trick.
Topic archived. No new replies allowed.