Input and Output
In Example 1.3, the directive
#include
allowed us to make use of the predefined global input and output stream objects.
They are
- 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 that flushes more often and is normally used for error messages
To send output to the screen in Example 1.3, we made use of the global stream object (of the class ostream), called cout. We called one of its member functions, whose name is operator<<(). This function overloads the insertion operator << and defines it like a global function.[9] The syntax for that output statement is also quite interesting. Instead of using the rather bulky function notation:
[9] We will discuss overloaded functions and operators in more detail later in Section 5.2.
cout.operator<<("Factorial of :");
we invoked the same function using the more elegant and readable infix syntax:
cout << "Factorial of:" ;
This operator 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." << ' ';
In Example 1.4, we can see the operator>>() used for input with istream in an analogous way to << for ostream.
Example 1.4. src/iostream/io.cpp
#include #include 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 that were added to the std namespace for convenience.[10] Manipulators are implicit calls to functions that can change the state of a stream object in various ways.
[10] We discuss these further in Section 1.10.
Notice also that we are using the string type from the Standard Library. We will discuss this type and demonstrate some of its functions shortly (see Section 1.9).
Exercises: Input and Output
1. |
Using Example 1.4, do the following experiments:
|
|
2. |
Consider the program shown in Example 1.5. Example 1.5. src/early-examples/fac2.cpp
|