stringstream
class, which allows you to associate an I / O stream with a string in memory. Everything that is output to such a stream is added to the end of the line; everything that is read from the stream is retrieved from the beginning of the line. #include <sstream> #include <iostream> int main(int argc, char* argv[]) { std::stringstream ss; ss << "22"; int k = 0; ss >> k; std::cout << k << std::endl; return 0; }
void func(int id, const std::string& data1, const std::string& data2) { std::stringstream ss; ss << "Operation with id = " << id << " failed, because data1 (" << data1 << ") is incompatible with data2 (" << data2 << ")"; std::cerr << ss.str(); }
stringstream
unnecessary, since the message could be output directly to cerr
. But what if you want to output the message not to the standard stream, but to use, say, the syslog()
function to output the message to the system log? Or, say, to generate an exception containing this string as an explanation: void func(int id, const std::string& data1, const std::string& data2) { std::stringstream ss; ss << "Operation with id = " << id << " failed, because data1 (" << data1 << ") is incompatible with data2 (" << data2 << ")"; throw std::runtime_error(ss.str()); }
stringstream
object in which you first form a string, and then get it using the str()
method. Agree cumbersome?stringstream
, which allows you to format a string anywhere in the code without additional variables, as if I were just outputting data to a stream: void func(int id, const std::string& data1, const std::string& data2) { throw std::runtime_error(MakeString() << "Operation with id = " << id << " failed, because data1 (" << data1 << ") is incompatible with data2 (" << data2 << ")"); }
MakeString
itself: class MakeString { public: template<class T> MakeString& operator<< (const T& arg) { m_stream << arg; return *this; } operator std::string() const { return m_stream.str(); } protected: std::stringstream m_stream; };
MakeString
class, the MakeString
operator (<<) is overloaded, which takes a constant reference to an object of any type as an argument, immediately prints this object to its internal stringstream
and returns a reference to itself. On the other hand, the conversion operator is overloaded to a string that returns the string formed by stringstream
.Source: https://habr.com/ru/post/131977/
All Articles