[   ^ to index...   |   <-- previous   |   next -->   ]

Formatted I/O

Both input and output can be formatted. However, rather than using format strings, we define the format of an operation by calling a method on the stream object:

// set hexadecimal output for integers cout.setf(ios_base::hex, ios_base::basefield); cout << 31 << endl; // Prints 1f // Set the minimum number of characters to print cout.width(4); cout << 1 << endl; // Prints 1 preceded by 3 spaces. // Set the "fill" character cout.fill('.'); cout.width(10); cout << "foo" << endl; // Prints "foo" preceded by 7 .'s char x[20]; cin.width(4); // Get up to 4 characters cin >> x; // x only gets words of 3 letters or less

Notes:

Manipulators

Manipulators are a weird little hack that allows you to insert formatting information into a line of output calls:

#include <iomanip.h> // The following prints "3.1416:" cout << setprecision(5) << 3.14159265 << ':' << flush; cin >> i; cout.width(5); cout << setfill('.') << i << endl;

Last modified: Wed Jun 28 20:19:48 PDT 2000