In Example 1.3, the directive
#include
allowed us to make use of the predefined global input and output stream objects.
They are
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
|
Part I: Introduction to C++ and Qt 4
C++ Introduction
Classes
Introduction to Qt
Lists
Functions
Inheritance and Polymorphism
Part II: Higher-Level Programming
Libraries
Introduction to Design Patterns
QObject
Generics and Containers
Qt GUI Widgets
Concurrency
Validation and Regular Expressions
Parsing XML
Meta Objects, Properties, and Reflective Programming
More Design Patterns
Models and Views
Qt SQL Classes
Part III: C++ Language Reference
Types and Expressions
Scope and Storage Class
Statements and Control Structures
Memory Access
Chapter Summary
Inheritance in Detail
Miscellaneous Topics
Part IV: Programming Assignments
MP3 Jukebox Assignments
Part V: Appendices
MP3 Jukebox Assignments
Bibliography
MP3 Jukebox Assignments