Chapter 2. Variables and Keyboard Input
In this chapter, you will accept input in another short program. You will learn about declaring variables and practice writing more functions. You’ll also start to think about general approaches to handling errors, which I’ll go into more in the next chapter. You’ll then be ready to start building a larger program in Chapter 3. The larger program will input and analyze stock-price data, and you will add to this project over the rest of the book.
First, you need to be able to take input, so let’s find out how. You will write a program in a single file again. If you need a reminder on how to build your code, look back at “Using Your Tools”.
When you wrote output, you used two approaches: std::println and std::cout’s operator <<. You have one option for input in C++ using an input stream std::cin.
Input needs to go somewhere, so you must start with a place for it.
Declaring Variables
Create a new source file and call it input.cpp. This will give you a place to experiment.
You will write a program to get input shortly, but first, you need a variable to take that input.
All variables in C++ have a type. You met int in the previous chapter as the return from main in Example 1-1.
You start with a type followed by a name.
You can explicitly state a value you want. For example:
intnumber=0;
However, a more general approach uses brace initialization, which means using {} after the variable name:
intnumber{};
The number is still initialized with ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access