Rearranging words in a string?

I'm just wondering if it's possible to use getline(cin, string) in some way so if the user were to input "Apple1 Apple2 Apple3", or "John D Doe", it would swap them around so the output would be "Apple3 Apple1 Apple2" or" Doe John D". I've been trying to find the simplest method but I can't seem to do it without individual cin inputs for the 3 apple names.
One way to do it is:

1, read the entire line of input into a string using std::getline.

2. create a stringstream from the string,

3. read from the stringstream the individual words into a temp string, and push back each word into a vector of strings.

4. reverse output each element of the vector.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
using namespace std;

string flip( const string &input )
{
   stringstream ss( input );
   vector<string> parts;
   for ( string s; ss >> s; ) parts.push_back( s );
   string result = parts.back() + ", " + parts.front();
   for ( int i = 1; i < parts.size() - 1; i++ ) result = result + " " + parts[i][0] + ".";
   return result;
}

int main()
{
   string tests[] = { "Donald John Trump", "Barack Hussain Obama", "George Herbert Walker Bush", "George Washington" };
   for ( string s : tests ) cout << flip( s ) << '\n';
}


Trump, Donald J.
Obama, Barack H.
Bush, George H. W.
Washington, George
Topic archived. No new replies allowed.