How to iterate through sentence

My program works when it is only one word. But how do i get it to work for a whole sentence. This an english to pig latin translator by the way. and i can only use functions from the string library.

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
 #include <iostream>
#include <string>



using namespace std;



int main() {
	
	
	string message, pig_message;
	
	bool on = true;

	while (true) {
		getline(cin, message);

		if (message[0] == 'a' || message[0] == 'e' || message[0] == 'i' ||
			message[0] == 'o' || message[0] == 'u') {
			pig_message = message + "yay";
			cout << pig_message << endl;

		}
		else if (message == " ") {
			on = false;
		}
		else {
			pig_message = message.substr(1) + message[0] + "ay";
			cout << pig_message << endl;
		}
	}
	
	

	system("pause");
	return 0;
}
i can only use functions from the string library.

The simplest approach would be to use a stringstream to read each word from the input string. However, that seems to be explicitly excluded, so in effect you have to recreate the same functionality for yourself.

That is to say, identify the breaks between words by the presence of whitespace (space or tab characters in this example (newline is also whitespace)).
You may find the following useful:
http://www.cplusplus.com/reference/string/string/find_first_of/
http://www.cplusplus.com/reference/string/string/find_first_not_of/
http://www.cplusplus.com/reference/string/string/substr/
Use the getline only version (commented out below) if you want the 'yay' at the end of the sentence or the stringstream version if you want a 'yay' after every word of the sentence

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <string>
#include <sstream>
using namespace std;

int main()
{
    string line;
    cout<<"Enter a sentence: \n";
    getline(cin, line);
 //   cout<< line + " yay";
    stringstream stream(line);
    string words;
    while (stream >> words)
    {
        cout<<words + " yay"<<"\n";
    }

}

edit: oops, just noticed string only, in that case above solution then
Last edited on
Topic archived. No new replies allowed.