typedef basic_istream istream;
All the classes mentioned earlier are defined via similar type definitions. There are also type definitions for all stream classes using wchar_t(the wide character type discussed in Chapter 3) instead of char. We’ll look at these at the end of this chapter. The basic_iostemplate defines functions common to both input and output, but that depends on the underlying character type (we won’t use these much). The template basic_istreamdefines generic functions for input, and basic_ostreamdoes the same for output. The classes for file and string streams introduced later add functionality for their specific stream types .
In the iostreams library, two operators are overloaded to simplify the use of iostreams. The operator <<is often referred to as an inserter for iostreams, and the operator >>is often referred to as an extractor .
Extractors parse the information that’s expected by the destination object according to its type. To see an example of this, you can use the cinobject, which is the iostream equivalent of stdinin C, that is, redirectable standard input. This object is predefined whenever you include the header .
int i;
cin >> i;
float f;
cin >> f;
char c;
cin >> c;
char buf[100];
cin >> buf;
There’s an overloaded operator >>for every built-in data type. You can also overload your own, as you’ll see later .
To find out what you have in the various variables, you can use the coutobject (corresponding to standard output; there’s also a cerrobject corresponding to standard error) with the inserter <<: .
cout << "i = ";
cout << i;
cout << "\n";
cout << "f = ";
cout << f;
cout << "\n";
cout << "c = ";
cout << c;
cout << "\n";
cout << "buf = ";
cout << buf;
cout << "\n";
This is notably tedious and doesn’t seem like much of an improvement over printf( ), despite improved type checking. Fortunately, the overloaded inserters and extractors are designed to be chained together into a more complicated expression that is much easier to write (and read): .
cout << "i = " << i << endl;
cout << "f = " << f << endl;
cout << "c = " << c << endl;
cout << "buf = " << buf << endl;
Defining inserters and extractors for your own classes is just a matter of overloading the associated operators to do the right things, namely:
· Make the first parameter a non- constreference to the stream ( istreamfor input, ostreamfor output)
· Perform the operation by insert/extracting data to/from the stream (by processing the components of the object, of course)
· Return a reference to the stream
The stream should be non- constbecause processing stream data changes the state of the stream. By returning the stream, you allow for chaining stream operations in a single statement, as shown earlier .
As an example, consider how to output the representation of a Dateobject in MM-DD-YYYY format. The following inserter does the job:
ostream& operator<<(ostream& os, const Date& d) {
char fillc = os.fill('0');
os << setw(2) << d.getMonth() << '-'
<< setw(2) << d.getDay() << '-'
<< setw(4) << setfill(fillc) << d.getYear();
return os;
}
This function cannot be a member of the Dateclass, of course, because the left operand of the <<operator must be the output stream. The fill( )member function of ostreamchanges the padding character used when the width of an output field, determined by the manipulator setw( ), is greater than needed for the data. We use a ‘0’ character so that months before October will display with a leading zero, such as "09" for September. The fill( )function also returns the previous fill character (which defaults to a single space) so that we can restore it later with the manipulator setfill( ). We discuss manipulators in depth later in this chapter .
Extractors require a little more care because things sometimes go wrong with input data. The way to signal a stream error is to set the stream’s fail bit , as follows:
istream& operator>>(istream& is, Date& d) {
is >> d.month;
char dash;
is >> dash;
if (dash != '-')
is.setstate(ios::failbit);
is >> d.day;
is >> dash;
if (dash != '-')
is.setstate(ios::failbit);
is >> d.year;
return is;
}
When an error bit is set in a stream, all further streams operations are ignored until the stream is restored to a good state (explained shortly). That’s why the code above continues extracting even if ios::failbitgets set. This implementation is somewhat forgiving in that it allows white space between the numbers and dashes in a date string (because the >>operator skips white space by default when reading built-in types). The following are valid date strings for this extractor: .
"08-10-2003"
"8-10-2003"
"08 - 10 - 2003"
but these are not:
"A-10-2003" // No alpha characters allowed
"08%10/2003" // Only dashes allowed as a delimiter
We’ll discuss stream state in more depth in the section "Handling stream errors" later in this chapter .
As the Dateextractor illustrated, you must be on guard for erroneous input. If the input produces an unexpected value, the process is skewed, and it’s difficult to recover. In addition, formatted input defaults to white space delimiters. Consider what happens when we collect the code fragments from earlier in this chapter into a single program: .
//: C04:Iosexamp.cpp
// Iostream examples
#include
using namespace std;
int main() {
int i;
cin >> i;
float f;
cin >> f;
char c;
cin >> c;
char buf[100];
cin >> buf;
cout << "i = " << i << endl;
cout << "f = " << f << endl;
cout << "c = " << c << endl;
cout << "buf = " << buf << endl;
cout << flush;
cout << hex << "0x" << i << endl;
} ///:~
and give it the following input: .
12 1.4 c this is a test
We expect the same output as if we gave it:
12
1.4
c
this is a test
but the output is, somewhat unexpectedly
i = 12
f = 1.4
c = c
buf = this
0xc
Notice that bufgot only the first word because the input routine looked for a space to delimit the input, which it saw after "this." In addition, if the continuous input string is longer than the storage allocated for buf, we overrun the buffer .
In practice, you’ll usually want to get input from interactive programs a line at a time as a sequence of characters, scan them, and then perform conversions once they’re safely in a buffer. This way you don’t have to worry about the input routine choking on unexpected data .
Another thing to consider is the whole concept of a command-line interface. This made sense in the past when the console was little more than a glass typewriter, but the world is rapidly changing to one in which the graphical user interface (GUI) dominates. What is the meaning of console I/O in such a world? It makes much more sense to ignore cinaltogether, other than for simple examples or tests, and take the following approaches: .
Читать дальше