"Illuzioner" <illuzioner@aol.com> wrote in message
news:20050108052355.07117.00002700@mb-m10.aol.com...[color=blue]
> hey all,
>
> can anyone enlighten me on the proper c++ way to print formatted text into[/color]
a[color=blue]
> string?[/color]
There are a couple of ways: Using a 'std::ostringstream'
object, or use 'sprintf()'.
[color=blue]
>
> e.g.
>
> string mytext;
> double nn=445566.332211;
>
> what is the proper equivalent of the following c type expression:
>
> sprintf(mytext,"%8.3f",nn); // this is wrong in c++!![/color]
It's wrong because you gave the wrong type argument to
'sprintf()'. So it's wrong in C as well.
#include <ios>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
int main()
{
double nn=445566.332211;
std::ostringstream oss;
oss << std::fixed << std::setprecision(6) << nn;
std::string mytext(oss.str());
std::cout << mytext << '\n';
return 0;
}
[color=blue]
>
> and then to add to it?
>
> mytext += more formatted text[/color]
oss.str("");
oss << " more text " << 42;
mytext += oss.str();
[color=blue]
>
> any ideas?[/color]
Yes, get this book:
www.josuttis.com/libbook
-Mike