Reading Formatted Input Sample

Description

We often associate stream I/O formatting with output operations, but it's equally possible to apply formatting techniques to input. A couple of simple examples of what this looks like are:

	bool b;
	cin >> boolalpha >> b;

	int i;
	cin >> hex >> i;
In the first case, the manipulator boolalpha is used so that an input value like true is recognized as a bool, rather than requiring that true be specified as 1. In the second case, the input stream of digits is interpreted as hexadecimal instead of decimal. Another common example of input formatting is use of skipws to skip whitespace on input.

User-defined types can also be input from a stream. The idea is to read the pieces of the type, and assemble them together (typically via a constructor) into an object of the type. For example, a Complex value such as:

	(12.34,97.65)
can be read by first reading the leading punctuation (, reading the first double value, reading the comma, reading the second double value, and finally reading the trailing ). An operator for such a type is declared as:
	istream& operator>>(istream&, Complex&);
and the Complex& parameter cannot be const, because it is used to store the actual value that is read in.

Checking the status of input operations can be done using a couple of state bits, for example:

	if (cin.rdstate() & ios_base::failbit)
		// failure

	if (cin.rdstate() & ios_base::eofbit)
		// end of file

	cin.clear(ios_base::failbit); // sets bit
Note that clear(), despite its name, is used to set status bits. ios_base::failbit indicates that an operation failed, for example if a program tried to read an int, and the first character available in the input stream was the letter Z. ios_base::eofbit indicates end of file.

Concept

The sample program uses istringstream in place of cin, and input is read from strings. Unformatted and formatted bool values are read in, and then a hexadecimal integer is read.

Then an attempt is made to read from the string abc into an integer, and ios_base::failbit is set to indicate that this operation failed. Next, input is done into a char[] object, and ios_base::eofbit is set to indicate that end of file (end of the string controlled by istringstream) was reached.

Finally, a value of type Complex is read in and displayed.

Supported
Supported
Supported