Game Development Reference
In-Depth Information
examples of
iostream
modifiers in action. One of the most common modifiers is
std::endl
and
earlier in the topic you also used the
std::hex
and
std::showbase
modifiers with
cout
. Listing 13-17
shows a method that uses a
stringstream
to format data into a
string
.
Listing 13-17.
stringstream
Modifiers
#include <iostream>
#include <sstream>
#include <iomanip>
#include <ios>
void StringStreamExample()
{
stringstream myStringStream;
myStringStream << "Hi" << endl;
cout << "width: " << myStringStream.width() << endl;
myStringStream << 123 << endl;
myStringStream << setw(10) << 123 << endl;
myStringStream << setw(0) << 123 << endl;
myStringStream << 123.567 << endl;
myStringStream << setprecision(4) << 123.567 << endl;
myStringStream << fixed << setprecision(2) << 123.567 << endl;
myStringStream << defaultfloat << setprecision(0) << 123.567 << endl;
myStringStream << 110 << endl << showbase;
myStringStream << hex << 110 << endl;
myStringStream << oct << 110 << endl;
myStringStream << dec << 110 << endl << noshowbase;
string myString = myStringStream.str();
cout << myString;
}
You can see in Listing 13-17 that you can use a
stringstream
object in the same way we have been
using the
cout
object to write to the console window. This means that all of the modifiers that are
available to
cout
are also available to
stringstream
and later in the topic you'll see how they're also
available when writing and reading files.
The specific examples of modifiers that you can see in Listing 13-17 are the
setw
,
setprecision
,
fixed
,
defaultfloat
,
showbase
,
noshowbase
,
hex
,
oct
, and
dec
modifiers. The
setw
modifier ensures
that the number specified is the minimum number of characters written to the stream. In this case
we will write the value 123 and 7 padding characters, in this case spaces, into the stream. We clear
the width by setting the value of the width back to 0.
The
setprecision
modifier is used to round numbers. This will round floating point values. The value
of 4 in the example will round 123.567 to 123.6. When we use the
fixed
modifier, we are telling
the stream to fix the number of decimal places using the value set by
setprecision
. Therefore
<< fixed << setprecision(2)
will round our number to 123.57. The last line related to floating point
values removes the fixed modifier by reinstating the
defaultfloat
setting and setting the precision
back to its default value of 0.