C++ Programming Fundamentals (Cyberrookies)

There are other ways of formatting text, other than the escape characters. Many of these are new to C++ and are not supported in C. In addition to formatting, your C++ compiler can also convert values of various types into characters. You can control formatting with certain C++ commands such as the following:

The following items are flags, rather than functions. A flag is a preset value that is used to determine a course of action. Flags are normally integer values, but often are given a name, or label, to make their value more readily apparent to human programmers. In this case, the flags determine how the setf function will format the output. This means that you simply set them to some value rather than call them, or pass them, parameters.

This next example illustrates several of the various formatting functions and properties that we have just discussed. This should allow you to see these items in action and get a much better feel for them.

Example 2.8

Step 1: Type the following code into your favorite text editor.

#include <iostream> #include <iomanip> // This header file is required for // the setprecision manipulator using namespace std; // this is a shortcut. Instead of // including each item in the std // namespace, just include them // all! int main() { cout << 2002 <<endl; cout << "In hex " << hex<< 2002 <<endl; cout.setf(ios::scientific,ios::floatfield); cout <<987.123456 <<endl; cout << setprecision(3) << 987.123456 <<endl; cout.fill('X'); cout.width(10); cout << 1234 <<endl; cout.setf(ios::left,ios::adjustfield); cout.width(10); cout << 1234 <<endl; return 0; }

Step 2: Compile your code.

Step 3: Run the executable. You should see something similar to the image shown in Figure 2.8.

Figure 2.8: Formatting.

This section is meant to introduce you to these formatting techniques. You will see many of them used again throughout the book, so you will get a chance to get more comfortable with them as we go.

Категории