Input/Output Formatting in C++


Input and output in C++ is type safe and easy for common formats using cin and cout. The following program listing shows some common uses:
#include <iostream.h>
#include <iomanip.h>

int main()
{
	int n;
	float f;
	double d;
	char s[100];

	// input an integer 
	cin >> n;
	// print an integer, no formatting 
	cout << n << endl;
	// print an integer, padded on left with spaces to total 6 chars 
	cout << setw(6) << n << endl;
	// print an integer, padded on right with spaces to total 6 chars 
	cout << setw(-6) << n << endl;

	// input a string (whitespace delineated) 
	cin >> s;
	// print a string, no formatting 
	cout << s << endl;
	// print a string, padded with spaces on left to 20 chars 
	cout << setw(20) << s << endl;
	// print a string, padded with spaces on right to 20 chars 
	cout << setiosflags(ios::left) << setw(20) << s << endl;

	// input a single precision floating point number 
	cin >> f;
	// print a float, default precision is 6 places 
	cout << setiosflags(ios::fixed) << f << endl;
	// input a double precision floating point number 
	cin >> d;
	// print a double, default precision is 6 places 
	cout << d << endl;
	// print a double, 2 places of precision 
	cout << setprecision(2) << d << endl;
	// print a double, 2 places of precision, padded with space to 10 
	cout << setw(10) << setprecision(2) << d << endl;
}

Rember that you can combine C routine sprintf and C++ cout. For example, if sprintf can give the desired formatting, use it to create the desired string, then output using C++ I/O. It is probably not a good idea to mix C and C++ input and output routines since they are buffered routines and may produce undesirable re-ordering of input/output.

Last updated 2001/10/08