Using the Standard Streams

Three specific streams are always available throughout the lifetime of every C++ program. These are the standard input, standard output, and standard error streams. Each of these standard streams has a specific use. The standard input stream reads data from the console, the standard output stream writes data to the console, and the standard error stream displays error messages to the console.

Programmers access the standard streams through a set of objects. Objects cin and cout provide access to the standard input and output streams, respectively. We have seen their use in previous examples. Object cerr provides access to the standard error stream. Listing 2 demonstrates use of the three standard streams.

1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: cout << "Enter your name and age: "; string name;int age; cin >> name >> age; if (age < 0) { cerr << "nInvalid age entered";}else { cout << "n" << name << " is " << age;}
Listing 2 Standard output and the << operator

Programmers do not have to explicitly open and close the three standard streams. These streams are automatically available for use (through their respective objects) when a program begins execution. Programmer's must explicitly open and close all other input and output streams.

C++ programmers can define how the classes they create interact with streams using the << and >> operators. This is called operator overloading. Remember, stream classes define the insertion (<<) and extraction (>>) to operate in a special way, for many different data types. Whether used with integers, floating point numbers, or strings, these operators output and format data accordingly. We can also define the behavior of these operators for classes that we create. This allows input and output code for user-defined classes to resemble input and output for built-in types.

1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: class Person {private: string first_name; string last_name; string job; public: Person (string f, string l, string j) : first_name(f), last_name(l), job(j) {} friend ostream& operator<<(ostream& os, Person const& r); }; ostream& operator<<(ostream& os, Person const& r) { os << r.first_name << " " << r.last_name; os << " works as a " << r.job; return os;}
Listing 3 A class that overloads <<

Listing 3 defines class Person. Since we would like to output objects of class Person the same way that we output integers or strings, we overload the << operator. Declaring this function as a "friend" function in line 11 allows the function to access private data members of class Person. This is necessary since the overloaded operator function is not a member of class Person.

1: 2: Person p("Stan", "Dardeviation", "Math Teacher");cout << p << endl;
Listing 4 Using class Person

The output of line 2 in Listing 4 follows.

Stan Dardeviation works as a Math Teacher
Example 1 Output of Listing 4