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

微笑、不失礼 提交于 2020-01-02 03:46:14

问题


I should know this already but... printf is to sprintf as cout is to ____? Please give an example.


回答1:


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



回答2:


#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



回答3:


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.




回答4:


 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"



回答5:


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



来源:https://stackoverflow.com/questions/5918121/whats-the-equivalent-of-cout-for-output-to-strings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!