-
Book Overview & Buying
-
Table Of Contents
The C++ Workshop
By :
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
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
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.
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.
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.
std::cout << "Please enter your first name(s): "; getline(std::cin, firstName);
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.
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.
std::cout << std::endl; std::cout << "Welcome " << firstName << " " << lastName << std::endl; std::cout << "You are " << age << " years old." << std::endl;
// 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;
}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
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.
Change the font size
Change margin width
Change background colour