Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Deciphering Object-Oriented Programming with C++ [WARNING: NOT FOR USE IN OTHER MATERIAL/SEE CONTRACT]

You're reading from   Deciphering Object-Oriented Programming with C++ [WARNING: NOT FOR USE IN OTHER MATERIAL/SEE CONTRACT] A practical, in-depth guide to implementing object-oriented design principles to create robust code

Arrow left icon
Product type Paperback
Published in Sep 2022
Publisher Packt
ISBN-13 9781804613900
Length 594 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Dorothy R. Kirk Dorothy R. Kirk
Author Profile Icon Dorothy R. Kirk
Dorothy R. Kirk
Arrow right icon
View More author details
Toc

Table of Contents (30) Chapters Close

Preface 1. Part 1: C++ Building Block Essentials
2. Chapter 1: Understanding Basic C++ Assumptions FREE CHAPTER 3. Chapter 2: Adding Language Necessities 4. Chapter 3: Indirect Addressing – Pointers 5. Chapter 4: Indirect Addressing – References 6. Part 2: Implementing Object-Oriented Concepts in C++
7. Chapter 5: Exploring Classes in Detail 8. Chapter 6: Implementing Hierarchies with Single Inheritance 9. Chapter 7: Utilizing Dynamic Binding through Polymorphism 10. Chapter 8: Mastering Abstract Classes 11. Chapter 9: Exploring Multiple Inheritance 12. Chapter 10: Implementing Association, Aggregation, and Composition 13. Part 3: Expanding Your C++ Programming Repertoire
14. Chapter 11: Handling Exceptions 15. Chapter 12: Friends and Operator Overloading 16. Chapter 13: Working with Templates 17. Chapter 14: Understanding STL Basics 18. Chapter 15: Testing Classes and Components 19. Part 4: Design Patterns and Idioms in C++
20. Chapter 16: Using the Observer Pattern 21. Chapter 17: Applying the Factory Pattern 22. Chapter 18: Applying the Adapter Pattern 23. Chapter 19: Using the Singleton Pattern 24. Chapter 20: Removing Implementation Details Using the pImpl Pattern 25. Part 5: Considerations for Safer Programming in C++
26. Chapter 21: Making C++ Safer 27. Assessments 28. Index 29. Other Books You May Enjoy

Recapping basic I/O

In this section, we’ll briefly review simple character-based input and output with the keyboard and monitor. Simple manipulators will also be reviewed to both explain the underlying mechanics of I/O buffers and to provide basic enhancements and formatting.

The iostream library

One of the easiest mechanisms for input and output in C++ is the use of the <iostream> library. The header file <iostream> contains definitions of data types istream and ostream. Instances of these data types, cin, cout, cerr, and clog, are incorporated by including the std namespace. The <iostream> library facilitates simple I/O and can be used as follows:

  • cin can be used in conjunction with the extraction operator >> for buffered input
  • cout can be used in conjunction with the insertion operator << for buffered output
  • cerr (unbuffered) and clog (buffered) can also be used in conjunction with the insertion operator, but for errors

Let’s review an example showcasing simple I/O:

#include <iostream>
using namespace std;  // we'll limit the namespace shortly
int main()
{
    char name[20];  // caution, uninitialized array of char
    int age = 0;
    cout << "Please enter a name and an age: ";
    cin >> name >> age; // caution, may overflow name var.
    cout << "Hello " << name;
    cout << ". You are " << age << " years old." << endl;
    return 0;
}

First, we include the <iostream> library and indicate that we’re using the std namespace to gain usage of cin and cout (more on namespaces later in this chapter). Next, we introduce the main() function, which is the entry point in our application. Here, we declare two variables, name and age, neither of which is initialized. Next, we prompt the user for input by placing the string "Please enter a name and an age: " in the buffer associated with cout. When the buffer associated with cout is flushed, the user will see this prompt on the screen.

The keyboard input string is then placed in the buffer associated with cout using the extraction operator <<. Conveniently, one mechanism that automatically flushes the buffer associated with cout is the use of cin to read keyboard input into variables, such as seen on the next line, where we read the user input into the variables name and age, respectively.

Next, we print out a greeting of "Hello" to the user, followed by the name entered, followed by an indication of their age, gathered from the second piece of user input. The endl at the end of this line both places a newline character '\n' into the output buffer and ensures that the output buffer is flushed – more of that next. The return 0; declaration simply returns a program exit status to the programming shell, in this case, the value 0. Notice that the main() function indicates an int for a return value to ensure this is possible.

Basic iostream manipulators

Often, it is desirable to be able to manipulate the contents of the buffers associated with cin, cout, and cerr. Manipulators allow the internal state of these objects to be modified, which affects how their associated buffers are formatted and manipulated. Manipulators are defined in the <iomanip> header file. Common manipulator examples include the following:

  • endl: Places a newline character ('\n') in the buffer associated with cout then flushes the buffer
  • flush: Clears the contents of the output stream
  • setprecision(int): Defines the precision (number of digits) used to output floating point numbers
  • setw(int): Sets the width for input and output
  • ws: Removes whitespace characters from the buffer

Let’s see a simple example:

#include <iostream>
#include <iomanip>
using namespace std;   // we'll limit the namespace shortly
int main()
{
    char name[20];     // caution; uninitialized array
    float gpa = 0.0;   // grade point average
    cout << "Please enter a name and a gpa: "; 
    cin >> setw(20) >> name >> gpa;  // won't overflow name
    cout << "Hello " << name << flush;
    cout << ". GPA is: " << setprecision(3) << gpa << endl;
    return 0;
}

In this example, first, notice the inclusion of the <iomanip> header file. Also, notice that setw(20) is used to ensure that we do not overflow the name variable, which is only 20 characters long; setw() will automatically deduct one from the size provided to ensure there is room for the null character. Notice that flush is used on the second output line – it’s not necessary here to flush the output buffer; this manipulator merely demonstrates how a flush may be applied. On the last output line with cout, notice that setprecision(3) is used to print the floating point gpa. Three points of precision account for the decimal point plus two places to the right of the decimal. Finally, notice that we add the endl manipulator to the buffer associated with cout. The endl manipulator will first insert a newline character ('\n') into the buffer and then flush the buffer. For performance, if you don’t need a buffer flush to immediately see the output, using a newline character alone is more efficient.

Now that we have reviewed simple input and output using the <iostream> library, let’s move forward by briefly reviewing control structures, statements, and looping constructs.

You have been reading a chapter from
Deciphering Object-Oriented Programming with C++ [WARNING: NOT FOR USE IN OTHER MATERIAL/SEE CONTRACT]
Published in: Sep 2022
Publisher: Packt
ISBN-13: 9781804613900
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image