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:
- The width() call only applies to the next << operation.
- Calling width(0) means "as many characters as needed".
Manipulators
You can insert some formatting information into a line of output calls:
#include // Prints "3.1416....7" cout << setprecision(5) << 3.14159265 << flush; cout.width(5); cout << setfill('.') << 7 << endl;
The file streams are defined in fstream.h:
#include 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;