Book Image

The C++ Workshop

By : Dale Green, Kurt Guntheroth, Shaun Ross Mitchell
Book Image

The C++ Workshop

By: Dale Green, Kurt Guntheroth, Shaun Ross Mitchell

Overview of this book

C++ is the backbone of many games, GUI-based applications, and operating systems. Learning C++ effectively is more than a matter of simply reading through theory, as the real challenge is understanding the fundamentals in depth and being able to use them in the real world. If you're looking to learn C++ programming efficiently, this Workshop is a comprehensive guide that covers all the core features of C++ and how to apply them. It will help you take the next big step toward writing efficient, reliable C++ programs. The C++ Workshop begins by explaining the basic structure of a C++ application, showing you how to write and run your first program to understand data types, operators, variables and the flow of control structures. You'll also see how to make smarter decisions when it comes to using storage space by declaring dynamic variables during program runtime. Moving ahead, you'll use object-oriented programming (OOP) techniques such as inheritance, polymorphism, and class hierarchies to make your code structure organized and efficient. Finally, you'll use the C++ standard library?s built-in functions and templates to speed up different programming tasks. By the end of this C++ book, you will have the knowledge and skills to confidently tackle your own ambitious projects and advance your career as a C++ developer.
Table of Contents (15 chapters)

Basic I/O Statements

I/O stands for input/output and is how we get information in and out of our programs. This can take many forms, from inputting text via a keyboard, to clicking buttons with our mouse, to loading a file, and so on. In this chapter, and in general moving forward, we're going to be sticking with text input/output. For this, we'll use the iostream header.

Throughout this section, we'll be reading directly from input with little to no data validation. In a working application, however, input would be strictly validated to ensure it's of the correct format, among other things. Our lack of this is strictly for example purposes only.

The iostream header contains everything we need to interface with our applications via the keyboard, allowing us to get data in and out of our application. This is accomplished through the std::cin and std::cout objects.

Note

The std:: prefix here denotes a namespace. This will be looked at in more depth later in the book, but for now we can just know they're used to group code.

There's a couple of ways we can read data from our keyboard. First, we can use std::cin with the extraction operator:

    std::cin >> myVar

This will put your input into the myVar variable and works for both string and integer types.

Observe the following code that has an std::cin object included:

// Input example.
#include <iostream>
#include <string>
int main()
{
    std::string name;
    int age;
    std::cout << "Please enter your name: ";
    std::cin >> name;
    std::cout << "Please enter you age: ";
    std::cin >> age;
    std::cout << name << std::endl;
    std::cout << age;
}

If we run this code in our compiler, we can see that we can enter our details and have them printed back to us:

Figure 1.12: Basic IO

Figure 1.12: Basic IO

If you tried to enter a name with a space in, you'll have run into an issue where only the first name was captured. This gives us more insight into how std::cin is working; namely that it will stop capturing input when it encounters a terminating character (space, tab, or new line). We can see now why only our first name was captured properly.

It's also useful to know that extractions, the >> operator, can be chained. This means that the following two examples of code are equivalent:

Example 1:

    std::cin >> myVar1;
    std::cin >> myVar2;

Example 2:

    std::cin >> myVar1 >> myVar2;

To avoid our strings being cut off when a terminating character, such as space, is encountered, we can pull the entirety of the users input into a single variable by using the getline function. Let's update our code using this function to get the user's name:

    std::cout << "Please enter your name: ";
    getline(std::cin, name); 

If we run the code again, we can now see that we're able to use spaces in our name and getline() will capture the whole input. Using getline() is nicer because it means we don't have to worry about the line issues that can come with using cin extraction directly.

Figure 1.13: Using getline() to capture entire input

Figure 1.13: Using getline() to capture entire input

When we use getline(), we read our user's input into a string, but that doesn't mean we can't use it to read integer values. To convert a string value into its integer equivalent, we have the std::stoi function. For example, the string "1" would be returned as int 1. Combining it with getline() is a good way to parse integer inputs:

    std::string inputString = "";
    int inputInt = 0;
    getline(std::cin, inputString);
    inputInt = std::stoi(inputString);

Regardless of which method we use, we need to ensure that we handle strings and numerical values correctly. For example, perhaps we have some code that expects the user to input a number:

    int number;
    std::cout << "Please enter a number between 1-10: ";
    std::cin >> number;

If the user inputs a string here, maybe they type five instead of inputting the number, the program won't crash, but our number variable won't be assigned a value. This is something we need to be aware of when getting input from our users. We need to ensure it's of the correct format before we try to use it in our programs.

Outputting text is as simple as making a call to std::cout, using the insertion operator, <<, to pass our data. This will accept both string and numerical values, so both the following code snippets will work as intended:

    std::cout << "Hello World";
    std::cout << 1;

As with the extraction operation, the insertion operator can be chained to build more complex outputs:

    std::cout << "Your age is " << age;

Finally, when outputting text there are times where we want to either start a new line or insert a blank one. For this, we have two options, \n and std::endl. Both of these will end the current line and move to the next. Given this, the following code snippets give the same output:

    std::cout << "Hello\nWorld\n!";
    std::cout << "Hello" << std::endl << "World" << std::endl << "!";endl

As mentioned earlier, there are other types of input and output associated with applications; however, most of the time, IO will be facilitated through some form of UI. For our purposes, these two basic objects, std::cin/std::cout, will suffice.

We will apply our knowledge of the getline() method and the std::cin, std:cout, and std::endl objects in the next exercise.

Exercise 3: Reading User Details

In this exercise, we're going to write an application that will allow you to input your full name and age. We'll then print this information out, formatting it into complete sentences. Perform the following steps to complete the exercise:

Note

The complete code for this exercise can be found here: https://packt.live/37qJdhF.

  1. Define the firstName, lastName, and age variables, which will hold our user's inputs, as shown in the following snippet:
    // IO Exercise.
    #include <iostream>
    #include <string>
    int main()
    {
        std::string firstName;
        std::string lastName;
        int age;

    Note

    We're going to be covering data types in their own chapter later, so don't worry if the exact nature of these variable types isn't clear at this point.

  2. Type in the following code, which will request the user to input their first name:
        std::cout << "Please enter your first name(s): ";
        getline(std::cin, firstName);
  3. We'll do the same for surnames, again using getline() using the following snippet:
        std::cout << "Please enter your surname: ";
        getline(std::cin, lastName);

    For our final input, we'll allow the users to input their age. For this, we can use cin directly because it's our last input, so we need not worry about terminating lines characters, and we're expecting a single numerical value.

  4. Type the following code to have the user input their age:
        std::cout << "Please enter your age: ";
        std::cin >> age;

    Note

    Again, it's only because we're writing simple example programs that we're trusting our users to input the correct data and not doing any validation. In a production environment, all user input data would be strictly validated before use.

  5. Finally, we'll present this information back to the user, making use of chained insertions to format complete strings and sentences using the following code:
        std::cout << std::endl;
        std::cout << "Welcome " << firstName << " " << lastName               << std::endl;
        std::cout << "You are " << age << " years old." << std::endl;
  6. The complete code looks like this:
    // IO Exercise.
    #include <iostream>
    #include <string>
    int main() 
    {
        std::string firstName;
        std::string lastName;
        int age;
        std::cout << "Please enter your first name(s): ";
        getline(std::cin, firstName);
        std::cout << "Please enter your surname: ";
        getline(std::cin, lastName);
        std::cout << "Please enter your age: ";
        std::cin >> age;
        std::cout << std::endl;
        std::cout << "Welcome " << firstName << " " << lastName               << std::endl;
        std::cout << "You are " << age << " years old." << std::endl;
    }
  7. Run our application now and test it with some data.

    For our test data (John S Doe, Age: 30), we obtain the following output:

    Figure 1.14: A small application that allows users to input various details

Figure 1.14: A small application that allows users to input various details

Thus, with the completion of this exercise, we have put together, through basic IO, a little program that allows users to enter some personal details. We will now move on the next topic—functions.