I would like std::ostringstream
to modify the string I pass it:
#include <string>
#include <iostream>
#include <sstream>
void My_Function(std::string& error_message)
{
std::ostringstream error_stream(error_message);
// For Nipun Talukdar:
/* Perform some operations */
if (/* operation failed */)
{
error_stream << "Failure at line: "
<< __LINE__
<< ", in source file: "
<< __FILE__
<< "\n";
}
return;
}
int main(void)
{
std::string error_message;
My_Function(error_message);
std::cout << "Error is: \""
<< error_message
<< "\"\n";
return 0;
}
With the above code, the output of error_message
is empty.
This is because, according to cppreference.com, the constructor of std::basic_ostream
that takes a std::stream
takes a const
reference to a std::string
. This means that std::basic_ostringstream
does not modify the string passed to it. The cited reference even says that std::ostringstream
makes a copy of the string passed to it.
To get around this, I changed my function:
void My_Second_Function(std::string& error_message)
{
std::ostringstream error_stream;
error_stream << "Failure at line: "
<< __LINE__
<< "\n";
error_message = error_stream.str(); // This is not efficient, making a copy!
return;
}
Is there a more efficient method to perform formatted output to a string, such as a direct write (i.e. without have to copy from the stream)?
I'm using Visual Studio 2010, which does not support C++11. Due to shop considerations, the justification of upgrading to 2013 did not pass. So I can't use C++11 or C++14 features.