Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a stringstream duplicate

I know I cannot copy a stringstream, but I am wondering if I can duplicate it so that I can create two strings with similar output specifiers.

Something like this

std::stringstream s1;
s1 << std::scientific << std::setprecision(4);
s1 << 0.01;

// Later on I want to create s2 given s1
std::stringstream s2;
// Copy formatting specifiers from s1 to s2, so that the effect is 
// s2 << std::scientific << std::setprecision(4);
s2 << 0.02;

My reason is that I am writing a function that takes a stringstream and I would like to know the width of some output before modifying the stringstream.

I have looked through most of the question on stringstream here and I couldn't find an answer to this specific case.

like image 371
Tohiko Avatar asked Mar 27 '26 15:03

Tohiko


1 Answers

You can copyfmt - copy formatting information.

s2.copyfmt(s1);

Alternatively you could save and restore flags with:

std::ios_base::fmtflags f = s1.flags();
s2.flags(f);
like image 163
KamilCuk Avatar answered Mar 29 '26 04:03

KamilCuk