How to insert a string to the beginning of a stringstream - c++

For example only and not the actual code:
stringstream ss;
ss << " world!";
string hello("Hello");
// insert hello to beginning of ss ??
Thanks for all the responses, I also found this code, which works:
ostringstream& insert( ostringstream& oss, const string& s )
{
streamsize pos = oss.tellp();
oss.str( s + oss.str() );
oss.seekp( pos + s.length() );
return oss;
}

You cannot do it without making at least one copy. One way:
std::stringstream ss;
ss << " world!";
const std::string &temp = ss.str();
ss.seekp(0);
ss << "Hello";
ss << temp;
This relies on the "most important const" to extend the lifetime of the temporary and avoid making an extra copy.
Or, simpler and possibly faster:
std::stringstream ss;
ss << " world!";
std::stringstream temp;
temp << "Hello";
temp << ss.rdbuf();
ss = std::move(temp); // or ss.swap(temp);
This borrows the rdbuf approach from this answer, since the interesting problem here is how to minimize copies.

the only way i can see is to create the string from stream and prefix your other string
string result = hello + ss.str();
its called a stream for a reason.

Assuming ss1 contains "hello"
ss1 << ss.rdbuf();
or
ss1 << "hello" << ss;
Refer this URL for more info:-
stringstream

Related

How to add string to stringstream?

I need to merge a lot of strings into one.
Something like this
stringstream ss;
string str_one = "hello ";
string str_two = "world!\n";
ss.add(str_one);
ss.add(str_two);
string result = ss.str();
but there is no add function into stringstream. How do I do this?
stringstream has operator<< overload to insert data into the stream. It would return a reference to the stream itself so you can chain multiple insertions.
ss << str_one << str_two;
std::cout << ss.str(); // hello world!
As an alternate, you can leverage fold expression(since C++17) to concatenate multiple strings.
template<typename ...T>
std::string concat(T... first){
return ((first+ ", ") + ...);
}
int main(){
std::string a = "abc", b = "def", c = "ghi", d = "jkl";
std::cout << concat(a, b, c, d); // abc, def, ghi,
}
The fold expression is expanded as below:
"abc" + ("def" + ("ghi" + "jkl"));
Demo
Very simple, all you have to do:
ss << " appended string";
You can use str() method like this:
std::string d{};
std::stringstream ss;
ss.str("hello this");
while(std::getline(ss, d)){
std::cout << d;
};

How can I obtain the length of a const stringstream's buffer without copying or seeking?

I have a const std::stringstream and a desire to find out how many bytes there are in its underlying string buffer.
I cannot seekg to the end, tellg then seekg to the start again, because none of these operations are available constly.
I do not want to get the str().size() because str() returns a copy and this may not be a trivial amount of data.
Do I have any good options?
(The stream itself is presented to me as const, only because it is a member of another type, and I receive a const reference to an object of that type. The stream represents the contents of a "document", its encapsulating object represents a CGI response and I am trying to generate an accurate Content-Length HTTP header line from within operator<<(std::ostream&, const cgi_response&).)
I've never been very comfortable with stream buffers, but this seems to work for me:
#include <iostream>
#include <sstream>
std::stringstream::pos_type size_of_stream(const std::stringstream& ss)
{
std::streambuf* buf = ss.rdbuf();
// Get the current position so we can restore it later
std::stringstream::pos_type original = buf->pubseekoff(0, ss.cur, ss.out);
// Seek to end and get the position
std::stringstream::pos_type end = buf->pubseekoff(0, ss.end, ss.out);
// Restore the position
buf->pubseekpos(original, ss.out);
return end;
}
int main()
{
std::stringstream ss;
ss << "Hello";
ss << ' ';
ss << "World";
ss << 42;
std::cout << size_of_stream(ss) << std::endl;
// Make sure the output string is still the same
ss << "\nnew line";
std::cout << ss.str() << std::endl;
std::string str;
ss >> str;
std::cout << str << std::endl;
}
The key is that rdbuf() is const but returns a non-const buffer, which can then be used to seek.
If you want to know the remaining available input size:
#include <iostream>
#include <sstream>
std::size_t input_available(const std::stringstream& s)
{
std::streambuf* buf = s.rdbuf();
std::streampos pos = buf->pubseekoff(0, std::ios_base::cur, std::ios_base::in);
std::streampos end = buf->pubseekoff(0, std::ios_base::end, std::ios_base::in);
buf->pubseekpos(pos, std::ios_base::in);
return end - pos;
}
int main()
{
std::stringstream stream;
// Output
std::cout << input_available(stream) << std::endl; // 0
stream << "123 ";
std::cout << input_available(stream) << std::endl; // 4
stream << "567";
std::cout << input_available(stream) << std::endl; // 7
// Input
std::string s;
stream >> s;
std::cout << input_available(stream) << std::endl; // 4
stream >> s;
std::cout << input_available(stream) << std::endl; // 0
}
This is similar to #Cornstalks solution, but positions the input sequence correctly.
This should work :))
#include <iostream>
#include <sstream>
#include <boost/move/move.hpp>
int main()
{
const std::stringstream ss("hello");
std::cout << boost::move(ss).str().size();
}

How to add multiple items to string in c++?

I know how to do it with cout:
cout << "string" << 'c' << 33;
But how to perform this so output is redirected to variable instead directly to standard out ?
const char* string << "string" << 'c' << 33; //doesn't work
Use std::stringstream from C++ standard library.
It works like the following:
std::stringstream ss;
ss << "string" << 'c' << 33;
std::string str = ss.str();
const char* str_ansi_c = str.c_str();
Keep in mind str still needs to be in the scope while you are using C-style str_ansi_c.
#include <sstream>
#include <iostream>
main()
{
std::stringstream ss;
ss << "string" << 'c' << 33;
std::string str = ss.str();
std::cout << str;
}

How to joining 2 variables in other variable

See the example to understand
int rnd = rand() %10;
string Folder = "c://foldername";
string final_name = Folder + rnd; // here the target
/* I want the result like that (random folder name)
foldername5
foldername10
foldername3
foldername20
foldername17
*/
Use std::stringstream as:
#include <sstream> //include this
std::stringstream ss;
ss << Folder << rnd;
string final_name = ss.str();
Or you can write this just in one line:
string final_name = stringbuilder() << Folder << rnd;
All that it needs a small utility class:
struct stringbuilder
{
std::stringstream ss;
template<typename T>
stringbuilder & operator << (const T &data)
{
ss << data;
return *this;
}
operator std::string() { return ss.str(); }
};
Using this class, you can create std::string on the fly as:
void f(const std::string & file ) {}
f(stringbuilder() << Folder << rnd);
std::string s = stringbuilder() << 25 << " is greater than " << 5 ;
In c++ you use stringstream to convert integers to strings.
int rnd = rand() %10;
string Folder = "c://foldername";
stringstream ss;
ss << Folder << rnd;
string final_name = ss.str(); // here the target
In C++ the best way to do this is to use a stringstream:
#include<sstream>
...
std::stringstream stream;
stream << "c://foldername" << rand() %10;
stream.str(); // now contains both path and number
Say this:
std::string final_name = Folder + std::to_string(rnd);
If you have an old compiler that doesn't support C++11, you can use boost::lexical_cast, or std::snprintf, or string streams.
Convert rnd (it is in integer type) to string type then do the same
string final_name = Folder + rnd;

how do i add a int to a string

i have a string and i need to add a number to it i.e a int. like:
string number1 = ("dfg");
int number2 = 123;
number1 += number2;
this is my code:
name = root_enter; // pull name from another string.
size_t sz;
sz = name.size(); //find the size of the string.
name.resize (sz + 5, account); // add the account number.
cout << name; //test the string.
this works... somewhat but i only get the "*name*88888" and... i don't know why.
i just need a way to add the value of a int to the end of a string
There are no in-built operators that do this. You can write your own function, overload an operator+ for a string and an int. If you use a custom function, try using a stringstream:
string addi2str(string const& instr, int v) {
stringstream s(instr);
s << v;
return s.str();
}
Use a stringstream.
#include <iostream>
#include <sstream>
using namespace std;
int main () {
int a = 30;
stringstream ss(stringstream::in | stringstream::out);
ss << "hello world";
ss << '\n';
ss << a;
cout << ss.str() << '\n';
return 0;
}
You can use string streams:
template<class T>
std::string to_string(const T& t) {
std::ostringstream ss;
ss << t;
return ss.str();
}
// usage:
std::string s("foo");
s.append(to_string(12345));
Alternatively you can use utilities like Boosts lexical_cast():
s.append(boost::lexical_cast<std::string>(12345));
Use a stringstream.
int x = 29;
std::stringstream ss;
ss << "My age is: " << x << std::endl;
std::string str = ss.str();
you can use lexecal_cast from boost, then C itoa and of course stringstream from STL