What is the equivalent of cout for output to strings?

I should know this already, but ... printf matches sprintf since cout matches ____ ? Give an example.

+6
source share
5 answers

It looks like you are looking for std::ostringstream .

Of course, C ++ streams do not use format specifiers, such as the C functions printf() -type; they use manipulators .

Example, as requested:

 #include <sstream> #include <iomanip> #include <cassert> std::string stringify(double x, size_t precision) { std::ostringstream o; o << std::fixed << std::setprecision(precision) << x; return o.str(); } int main() { assert(stringify(42.0, 6) == "42.000000"); return 0; } 
+13
source
  std::ostringstream 

You can use this to create something like a Boost lexical throw:

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

Using:

 string is = ToString( 42 ); // is contains "42" string fs = ToString( 1.23 ) ; // fs contains something approximating "1.23" 
+1
source
 #include <iostream> #include <sstream> using namespace std; int main() { ostringstream s; s.precision(3); s << "pi = " << fixed << 3.141592; cout << s.str() << endl; return 0; } 

Conclusion:

 pi = 3.142 
+1
source

Here is an example:

 #include <sstream> int main() { std::stringstream sout; sout << "Hello " << 10 << "\n"; const std::string s = sout.str(); std::cout << s; return 0; } 

If you want to clear the stream for reuse, you can do

 sout.str(std::string()); 

Also check out the Boost Format library.

+1
source

You have a slight misunderstanding for the cout concept. cout is a stream, and the operator <is defined for any stream. So you just need another stream that writes to a string to output your data. You can use a standard stream, for example std :: ostringstream, or define your own.

So your analogy is not very accurate, since cout is not a function of printf and sprintf

-1
source

Source: https://habr.com/ru/post/887492/


All Articles