printing to a string class variable

I

Illuzioner

hey all,

can anyone enlighten me on the proper c++ way to print formatted text into a
string?

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++!!

and then to add to it?

mytext += more formatted text

any ideas?

thnx a bunch:)

lou
 
J

JH Trauntvein

The most appropriate way to format into a string value is to use
std::eek:stringstream declared in <sstream>.

Regards,

Jon Trauntvein
 
J

Jon Bell

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++!!

and then to add to it?

mytext += more formatted text

The key concept is "stringstream".

#include <iostream>
#include <iomanip>
#include <string>
#include <sstream>

using namespace std;

int main ()
{
string mytext;
ostringstream mytextstream;
double nn = 445566.332211;

// do output to a stringstream just like to cout or to a file

mytextstream << fixed << showpoint;
mytextstream << setw(8) << setprecision(3) << nn;
mytextstream << " is the number.";

// extract the contents of the stringstream to a string

mytext = mytextstream.str();
mytext += " Is this OK?\n";

cout << mytext;

return 0;;
}
 
M

Mike Wahler

Illuzioner said:
hey all,

can anyone enlighten me on the proper c++ way to print formatted text into a
string?

There are a couple of ways: Using a 'std::eek:stringstream'
object, or use 'sprintf()'.
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++!!

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::eek:stringstream oss;
oss << std::fixed << std::setprecision(6) << nn;
std::string mytext(oss.str());
std::cout << mytext << '\n';
return 0;
}


and then to add to it?

mytext += more formatted text

oss.str("");
oss << " more text " << 42;
mytext += oss.str();

any ideas?

Yes, get this book:
www.josuttis.com/libbook

-Mike
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,197
Messages
2,571,040
Members
47,634
Latest member
RonnyBoelk

Latest Threads

Top