c++c++14c++20stdstringistringstream

Can we create std::istringstream object from a reversed std::string


I am learning C++ using recommended C++ books. In particular, i read about std::istringstream and saw the following example:

std::string s("some string");
std::istringstream ss(s);
std::string word;
while(ss >> word)
{
    std::cout<<word <<" ";
}

Actual Output

some string

Desired Output

string some

My question is that how can we create the above std::istringstream object ss using the reversed string(that contains the word in the reverse order as shown in the desired output)? I looked at std::istringstream's constructors but couldn't find one that takes iterators so that i can pass str.back() and str.begin() instead of passing a std::string.


Solution

  • You can pass iterators to the istringstream constructor indirectly if you use a temporary string:

    #include <sstream>
    #include <iostream>
    
    int main()
    {
        std::string s{"Hello World\n"};
        std::istringstream ss({s.rbegin(),s.rend()});
        std::string word;
        while(ss >> word)
        {
            std::cout<<word <<" ";
        }
    }
    

    Output:

    dlroW olleH 
    

    Though thats reversing the string, not words. If you want to print words in reverse order a istringstream alone does not help much. You can use some container to store the extracted words and then print them in reverse:

    #include <sstream>
    #include <iostream>
    #include <vector>
    
    int main()
    {
        std::string s{"Hello World\n"};
        std::istringstream ss(s);
        std::string word;
        std::vector<std::string> words;
        while(ss >> word)
        {
            words.push_back(word);
        }
        for (auto it = words.rbegin(); it != words.rend(); ++it) std::cout << *it << " ";
    }
    

    Output:

    World Hello