string manipulation functions?

Hi. I've written a program for a beginner C++ class that asks the user to enter a generic five-word phrase (with a single space between). It then outputs each word of the phrase separately. The program runs fine and doesn't terminate or skip words if the user accidentally enters a double space. But my instructions say to use various string manipulation functions. How do I add those to my program? Here is the program:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <iomanip>
#include <string>

using namespace std;

int main ()
{
	string firstWord, secondWord, thirdWord, fourthWord, fifthWord;

	cout << "Enter a five-word phrase." << endl;
	cin >> firstWord >> secondWord >> thirdWord >> fourthWord >> fifthWord;

	cout << "Your first word is: " << firstWord << endl
		<< "Your second word is: " << secondWord << endl
		<< "Your third word is: " << thirdWord << endl
		<< "Your fourth word is: " << fourthWord << endl
		<< "Your fifth word is: " <<fifthWord << endl;

	return 0;
}
Start with
1
2
3
4
5
6
7
int main()
{
	string five_word_phrase;

	cout << "Enter a five-word phrase: ";
	getline( cin, five_word_phrase );

Now take a look through the string class's methods
http://www.cplusplus.com/reference/string/string/
to see what you can use to split the individual words out of the five_word_phrase string.

Hope this helps.

[edit]
Hint: you will need two indices into the string: where the next word starts and where it ends. Find those locations, then you can use another method to get only that substring.
Last edited on
I've been reading the reference site you suggested and also a book that I have, and I've come up with:
1
2
3
4
5
6
7
8
9
10
int main ()
{
	string firstWord, secondWord, thirdWord, fourthWord, fifthWord;

	cout << "Enter a five-word phrase." << endl;
	getline (cin, firstWord);
	getline (cin, secondWord);
	getline (cin, thirdWord);
	getline (cin, fourthWord);
	getline (cin, fifthWord);

, but I'm going about it all wrong. I still don't know how to split the words and get them to output separately. I know it has something to do with where the cursor is and how it reads spaces, but don't know how to write it. Also, I don't know what the cout statement would be.
The getline() function reads a line, not just a word. So by saying getline so many times you just put your program to read more lines... So you just need one getline() that will store all the words in a single string.

Hint: you will need two indices into the string: where the next word starts and where it ends

When you have a phrase, like "This is a phrase", what is the key to separate each word? It is like reading it.
Topic archived. No new replies allowed.