开发者

What's the equivalent of cout for output to strings?

开发者 https://www.devze.com 2023-03-03 18:51 出处:网络
I should know this already but..开发者_JAVA技巧. printf is to sprintf as cout is to ____? Please give an example.It sounds like you are looking for std::ostringstream.

I should know this already but..开发者_JAVA技巧. printf is to sprintf as cout is to ____? Please give an example.


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

Of course C++ streams don't use format-specifiers like C's printf()-type functions; 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;
}


#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;
}

Output:

pi = 3.142


Here's 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 look at the Boost Format library.


 std::ostringstream

You can use this to create something like the Boost lexical cast:

#include <sstream>
#include <string>

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

In use:

string is = ToString( 42 );      // is contains "42"
string fs = ToString( 1.23 ) ;   // fs contains something approximating "1.23"


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

So your analogy is not very precise, since cout is not a function like printf and sprintf

0

精彩评论

暂无评论...
验证码 换一张
取 消