"Filling" up the content of an empty stringstream

I have the following code chunk from a large project,
why isn't the for_each() working? It is supposed to
"fill" the stringstream object
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include<iostream> //standard input/output stream
#include<sstream> //for stringstream
#include<algorithm> //for std::sort && std::for_each
#include<vector> //for std::vector

int main()
{
    std::stringstream ss;
    std::string str;
    std::vector<std::string> vec;
    for(const auto &i: {"B", "C", "D", "A"})
        ss << i <<std::endl;
    while(ss >> str)
        vec.push_back(str);
    ss.str(""); /** clear the content of the stringstream **/
    std::sort(vec.begin(),vec.end(), [=](const std::string &s, const std::string &c)->bool { return s<c;});
    // here's the problem, it seems "ss << s" isn't working
    std::for_each(vec.cbegin(), vec.cend(), [&](const std::string &s) mutable { ss << s;});
    //for(const auto &i: vec) std::cout<<i<<std::endl;  //WORKS
    std::cout<<ss.str()<<std::endl;
    return 0;
}
At the end of the while loop, the ss.fail() flag will be true, it needs to be cleared before continuing to use ss.

1
2
3
4
    while(ss >> str)
        vec.push_back(str);
    ss.clear();  // clear the fail flag
    ss.str("");  // empty the stream contents 
Topic archived. No new replies allowed.