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

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:

cout.width(4); // Set the min no. of chars to print cout << 1 << endl; // Prints 1 preceded by 3 spaces. cout.fill('.'); // Set the "fill" character cout.width(10); cout << "foo" << endl; // Prints "foo" preceded by 7 .'s char x[20]; cin.width(4); // Get up to 4 characters, incl. null cin >> x; // x only gets words of 3 letters or less

Notes:

Manipulators

You can insert some formatting information into a line of output calls:

#include <iomanip.h> // Prints "3.1416....7" cout << setprecision(5) << 3.14159265 << flush; cout.width(5); cout << setfill('.') << 7 << endl;

File streams

The file streams are defined in fstream.h:

#include <fstream.h> ifstream in("in.txt"); ofstream out("out.txt"); if (!in) { cout << "Unable to open input file." << endl; } if (!out) { cout << "Unable to open output file." << endl; } in >> buf; out << buf;

Last modified: Wed Jun 28 20:54:26 PDT 2000