Search code examples
c++stringiteratorostream

How can I convert the output from a ostream_iterator to a string?


I am implementing a toString method in C++ primarily using the ostream_iterator.

std::ostream_iterator<int> output(std::cout, " ");

After printing to the console, however, I wish to return the output of the ostream_iterator as a string. Is this direct conversion possible?


Solution

  • Is this direct conversion possible?

    I think, no, because ostream_iterator is used to send data to stream one way, so if the destination is std::cout you cannot use ostream_iterator to get data back.

    But you can use some other destination, e.g. ostringstream object, and then use it for both output through cout and use again as you like.

    Consider simple example:

        std::stringstream buff;
        std::ostream_iterator<int> output(buff, " ");
        std::istringstream str("10 3 ABC 7 1");
        // just copy only first integer values from str (stop on the first non-integer)
        std::copy(std::istream_iterator<int>(str), std::istream_iterator<int>(), output);
        // output as a string to std output
        std::cout << buff.str() << std::endl;
        // do something else
        buff.seekp(0, std::ios::end);
        std::cout << "String size is " << buff.tellp() << std::endl;