I’m reading C++ Primer and working on its exercise. It want me to get user’s input and separate by space ' '. So I come up with 2 solution.
First solution:
vector<string> vector1;
string input;
string temp = ""; // temperary hold each word value in input.
string x1 = "";
char x2 = 'b';
x1 += x2;
cout << x1 << endl;
getline(cin, input);
input += " ";
for (string::size_type index = 0; index != input.size(); index++)
{
if (!isspace(input[index]))
{
temp += input[index];
}
else
{
if (temp.size() > 0)
{
vector1.push_back(temp);
temp = "";
}
}
}
Second solution
vector<string> vector1;
string input;
string temp = ""; // temperary hold each word value in input.
string x1 = "";
char x2 = 'b';
x1 += x2;
cout << x1 << endl;
getline(cin, input);
//input += " ";
for (string::size_type index = 0; index != input.size(); index++)
{
if (!isspace(input[index]))
{
temp += input[index];
}
else
{
if (temp.size() > 0)
{
vector1.push_back(temp);
temp = "";
}
}
}
if (!temp.empty())
{
vector1.push_back(temp);
}
The difference between them is first solution is add space to user input while second solution check that I don’t add last word or not. I want to know which one is better solution for this problem?
If there’re better solutions, please tell me.
I would write this:
It is almost same as @K-ballo’s answer, except that I let
std::copyread directly from input stream (i.estd::cin) rather than fromstd::stringstream.Demo: http://www.ideone.com/f0Gtc
—
Or you could make use of vector’s constructor, avoiding
std::copyaltogether:And you’re done! Demo : http://www.ideone.com/Szfes
If you find it difficult to read, then use this instead:
Demo : http://www.ideone.com/PDcud