3 Strings in one row

Hello, is there any simple solution how to get 3 string divided by white space '_' ?

Input:
Hello bye no
s1 = "Hello"
s2 = "bye"
s3 = "no"

i must separate it somehow because if i write only 2 or 1 word it should say "Wrong input" so i cant use cin >> s1 >> s2 >> s3;

1
2
3
4
5
6
7

    string s1, s2, s3;
    cout << "Enter three words:" << '\n';
    cin >> s1;
    getline(cin, head);
    
closed account (N36fSL3A)
Well, yes. Use stringstream.

1
2
3
4
5
6
7
8
9
10
std::stringstream ss[3];
ss[0] >> s1;
ss[1] >> s2;
ss[3] >> s3;

std::string str1, str2, str3;

str1 = ss[0].str();
str2 = ss[1].str();
str3 = ss[2].str();


Don't forget to #include<sstream>
Last edited on
sorry but i don't get it :( i should use stringstream with getline or how ? if i use it with cin >> s1 >> s2 >> s3; i still cant check if somebody write one word and then put enter...
closed account (N36fSL3A)
Sorry, ignore my post above...

Try something like this:

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 <vector>
#include <string>
#include <sstream>

int main()
{
	// Vector for holding string contents
	std::vector<std::string> tokens;

	std::string str;
	
	// Get input
	std::getline(std::cin, str);	

	std::string buffer = ""; // A buffer for words

	// String Stream for breaking up tokens.
	std::stringstream ss(str);

	while (ss >> buffer)
	{
		tokens.push_back(Buffer);
	}

	for(unsigned int i = 0; i < tokens.size()
	{
		std::cout << buffer[i] << "\n";
	}

	return 0;
}
Topic archived. No new replies allowed.