Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 374
Qwertie Avatar asked May 06 '11 23:05

Qwertie


2 Answers

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;
}
like image 63
Johnsyweb Avatar answered Nov 12 '22 14:11

Johnsyweb


#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
like image 22
Mark Tolonen Avatar answered Nov 12 '22 16:11

Mark Tolonen