[ fromfile: cppintro.xml id: stdinout ]
In Example 1.1, the directive
#include <iostream>
allowed us to make use of predefined global input (istream) and output (ostream) objects.
cin, standard input, the keyboard by default.
cout, standard output, the console screen by default
cerr, standard error, another output stream to the console screen which flushes more often, and is normally used for error messages.
In Example 1.1, we made use of the global ostream object, cout.
We called one of its member functions, whose name is operator <<().
This function overloads the operator, <<, and is used to insert data into the output stream - so we call it the insertion operator.
[2]
The syntax for that output statement is also quite interesting.
Instead of using the rather bulky function notation,
cout.operator<<("Factorial of :");
we invoked the same function using the more elegant and readable infix syntax:
cout << "Factorial of: " ;
This operator can be chained (used on multiple values), and is predefined for use with many built-in types, as we see in the next output statement.
cout << "The cost is $" << 23.45 << " for " << 6 << " items." << '\n';
In Example 1.2, we can see the operator>>() used for input with the istream object cin in an analogous way to the way we used << for output with the ostream object cout. Since the effect of this operator is to extract data from the input stream, we call this the extraction operator. [3]
Example 1.2. src/iostream/io.cpp
#include <string>
#include <iostream>
int main() {
using namespace std;
const int THISYEAR = 2006;
string yourName;
int birthYear;
cout << " What is your name? " << flush;
cin >> yourName;
cout << "What year were you born? " ;
cin >> birthYear;
cout << "Your name is " << yourName
<< " and you are approximately "
<< (THISYEAR - birthYear)
<< " years old. " << endl;
}
The symbols, flush and endl are manipulators [4], from the std namespace.
In Example 1.2, we make use of the string class [5], also from the C++ Standard Library.
We will discuss this type and demonstrate some of its functions later in Section 1.7.
[2] We cover overloaded functions and operators further in Section 5.2. This particular operator already has a name and definition from C. It is the left shift operator. For example, n << 2 shifts the bits of the int n two positions to the left, and fills the vacated bits with zeros - effectively multiplying n by 4.
[3] This time we have overloaded the right shift operator. n >> 2 shifts the bits of the int n two positions to the right, effectively dividing by 4, and fills the vacated bits appropriately depending on whether n is signed or unsigned.
[4] Manipulators are function references that can be inserted into an input or output stream to modify its state. We discuss these further in Section 1.8
| Generated: $Date: 2009-09-08 12:15:32 -0400 (Tue, 08 Sep 2009) $ | © 2009 Alan Ezust and Paul Ezust. |