is it possible insert a string to the beginning of a stringstream?

May 16, 2022 at 9:20am
has the title states, i am wondering if it is possible to insert a string at the front of a stringstream buffer?
May 16, 2022 at 9:36am
Since stringstream is also an ostream you can use seekp(...) to change the write position to the beginning of the stream. See:

http://www.cplusplus.com/reference/ostream/ostream/seekp/
May 16, 2022 at 9:37am
Well, you can seek to the beginning of the stream, so that the next write operation goes there, but that will overwrite the existing content, rather than "inserting" it in front of the existing content:

1
2
3
4
5
6
7
8
int main()
{
	std::stringstream sstream;
	sstream << "foo";
	sstream.seekp(0);
	sstream << "x";
	std::cout << sstream.str() << std::endl;
}


You could do something like this, but it may not be the most efficient way (creates a temporary copy):
1
2
sstream.seekp(0);
sstream << sstream.str().insert(0, "bar");
Last edited on May 16, 2022 at 9:42am
May 16, 2022 at 9:45am
A stringstream acts like a file stream. You can't insert at the beginning of a file so you can't insert at the beginning of a stringstream.

You can, however, 'cheat' with something like:

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <sstream>
#include <string>

int main() {
	std::ostringstream oss("foo");
	const auto s {oss.str()};

	oss.seekp(0);
	oss << "bar" << s;

	std::cout << oss.str() << '\n';
}



barfoo

May 16, 2022 at 10:23am
> insert a string at the front of a stringstream buffer?

We can use the member function str() to manage (get or set) the string stream's underlying string object.

For example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <sstream>
#include <string>

std::istringstream& push_front( std::istringstream& sstm, const std::string& str )
{
    sstm.str( str + sstm.str() ) ;
    sstm.seekg(0) ;
    return sstm ;
}

int main()
{
    std::istringstream sstm ( "five six seven" );

    std::string str ;
    sstm >> str ; // five
    std::cout << str << '\n' ;

    for( std::string temp : { "zero ", "one ", "two ", "three " } ) push_front( sstm, temp ) ;
    while( sstm >> str ) std::cout << str << ' ' ; // three two one zero five six seven
    std::cout << '\n' ;
}

http://coliru.stacked-crooked.com/a/1d3c2fc7416b6a0b
Topic archived. No new replies allowed.