C ++: what are the advantages of streaming streams?

can someone tell me about some practical examples of using string streams in C ++, i.e. input and output into a stream of strings using stream and stream insert operators?

+6
c ++ string stringstream
source share
4 answers

You can use string streams to convert everything that operator << implements into a string:

 #include <sstream> template<typename T> std::string toString(const T& t) { std::ostringstream stream; stream << t; return stream.str(); } 

or even

 template <typename U, typename T> U convert(const T& t) { std::stringstream stream; stream << t; U u; stream >> u; return u; } 
+11
source share

I use them mainly as memory buffers when creating messages:

 if(someVector.size() > MAX_SIZE) { ostringstream buffer; buffer << "Vector should not have " << someVector.size() << " eleements"; throw std::runtime_error(buffer.str()); } 

or to build complex strings:

 std::string MyObject::GenerateDumpPath() { using namespace std; std::ostringstream dumpPath; // add the file name dumpPath << "\\myobject." << setw(3) << setfill('0') << uniqueFileId << "." << boost::lexical_cast<std::string>(state) << "_" << ymd.year << "." << setw(2) << setfill('0') << ymd.month.as_number() << "." << ymd.day.as_number() << "_" << time.hours() << "." << time.minutes() << "." << time.seconds() << ".xml"; return dumpPath.str(); } 

This is useful because it brings the full extensibility of std::stream to the use of character buffers (support for extensibility and ostreams locales, buffer memory management, etc.).

Another example I saw is an error message in the gsoap library using dependency injection: soap_stream_fault accepts the ostream command & parameter to report error messages.

If you want, you can pass it std :: cerr, std :: cout or std :: ostringstream (I use it with the implementation of std :: ostringstream).

+3
source share

Beyond the benefits, there is one point to consider carefully if you are using gcc 4.3.1. I have not tested previous versions of gcc.

+2
source share

They can be used wherever a regular stream can be used.

So, in situations where you read from a file, you could read from a stream of lines.

 void compile(std::istream& str) { CPlusPlusLexer lexer(str); CPlusPlusParser parser(lexer); BackEnd backend(parser); backend.compile(); } int main() { std::fstream file("Plop.cpp"); compile(file); std::stringstream test("#include <iostream>\n int main() { std::cout << \"H World\n\";}"); compile(test); } 
+2
source share

All Articles