Objectives
In this chapter, you’ll:
■ Write simple C++ applications.
■ Use input and output statements.
■ Use fundamental data types.
■ Use arithmetic operators.
■ Understand the precedence of arithmetic operators.
■ Write decision-making statements.
■ Use relational and equality operators.
■ Begin appreciating the “objects natural” learning approach by creating and using objects of the C++ standard library’s string
class before creating your own custom classes.
Outline
2.2 First Program in C++: Displaying a Line of Text
2.3 Modifying Our First C++ Program
2.4 Another C++ Program: Adding Integers
2.6 Decision Making: Equality and Relational Operators
2.7 Objects Natural: Creating and Using Objects of Standard Library Class string
This chapter presents several code examples that demonstrate how your programs can display messages and obtain data from the user for processing. The first three display messages on the screen. The next obtains two numbers from a user at the keyboard, calculates their sum and displays the result—the accompanying discussion introduces C++’s arithmetic operators. The fifth example demonstrates decision making by showing you how to compare two numbers, then display messages based on the comparison results.
In your programs, you’ll create and use many objects of carefully-developed-and-tested preexisting classes that enable you to perform significant tasks with minimal code. These classes typically come from:
• the C++ standard library,
• platform-specific libraries (such as those provided by Microsoft for creating Windows applications or by Apple for creating macOS applications) and
• free third-party libraries often created by the massive open-source communities that have developed around all major contemporary programming languages.
To help you appreciate this style of programming early in the book, you’ll create and use objects of preexisting C++ standard library classes before creating your own custom classes. We call this the “objects natural” approach. You’ll begin by creating and using string
objects in this chapter’s final example. In later chapters, you’ll create your own custom classes. You’ll see that C++ enables you to “craft valuable classes” for your own use and that other programmers can reuse.
For instructions on compiling and running programs in Microsoft Visual Studio, Apple Xcode and GNU C++, see the test-drives in Chapter 1 or our video instructions at
http://deitel.com/c-plus-plus-20-for-programmers
You are viewing an early-access “rough cut” of C++20 for Programmers. We prepared this content carefully, but it has not yet been reviewed or copy edited and is subject to change. As we complete each chapter, we’ll post it here. Please send any corrections, comments, questions and suggestions for improvement to paul@deitel.com
and I’ll respond promptly. Check here frequently for updates.
As an O’Reilly Online Learning subscriber, you also have access to the “sneak peek” of our new C++20 Fundamentals LiveLessons videos at:
https://learning.oreilly.com/videos/c-20-fundamentals-parts/9780136875185
Co-author Paul Deitel immediately records each video lesson as we complete each rough-cut e-book chapter. Lessons go live on O’Reilly Online Learning a few days later. Again, check here frequently for updates.
Consider a simple program that displays a line of text (Fig. 2.1). The line numbers are not part of the program.
Fig. 2.1 Text-printing program.
Lines 1 and 2
// fig02_01.cpp // Text-printing program.
each begin with //
, indicating that the remainder of each line is a comment. In each of our programs, the first line comment contains the program’s file name. The comment "Text-printing program."
describes the purpose of the program. A comment beginning with //
is called a single-line comment because it terminates at the end of the current line. You can create multiline comments by enclosing them in /*
and */
, as in
/* fig02_01.cpp Text-printing program. */
#include
Preprocessing DirectiveLine 3
#include <iostream> // enables program to output data to the screen
is a preprocessing directive—that is, a message to the C++ preprocessor, which the compiler invokes before compiling the program. This line notifies the preprocessor to include in the program the contents of the input/output stream header <iostream>
. This header is a file containing information the compiler requires when compiling any program that outputs data to the screen or inputs data from the keyboard using C++’s stream input/output. The program in Fig. 2.1 outputs data to the screen. Chapter 5 discusses headers in more detail, and Chapter 15 explains the contents of <iostream>
in more detail.
Line 4 is simply a blank line. You use blank lines, spaces and tabs to make programs easier to read. Together, these characters are known as white space—they’re normally ignored by the compiler.
main
FunctionLine 6
int main() {
is a part of every C++ program. The parentheses after main
indicate that it’s a function. C++ programs typically consist of one or more functions and classes. Exactly one function in every program must be named main
. Figure 2.1 contains only one function. C++ programs begin executing at function main
. The keyword int
to the left of main
indicates that after main
finishes executing, it “returns” an integer (whole number) value. Keywords are reserved by C++ for a specific use. We show the complete list of C++ keywords in Chapter 3. We’ll explain what it means for a function to “return a value” when we demonstrate how to create your own functions in Chapter 5. For now, simply include the keyword int
to the left of main
in each of your programs.
The left brace, {
, (end of line 6) must begin each function’s body, which contains the instructions the function performs. A corresponding right brace, }
, (line 10) must end each function’s body.
Line 7
std::cout << "Welcome to C++!\n"; // display message
displays the characters contained between the double quotation marks. Together, the quotation marks and the characters between them are called a string, a character string or a string literal. We refer to characters between double quotation marks simply as strings. White-space characters in strings are not ignored by the compiler.
The entire line 7—including std::cout
, the << operator, the string "Welcome to C++!\n"
and the semicolon (;
)—is called a statement. Most C++ statements end with a semicolon. Omitting the semicolon at the end of a C++ statement when one is needed is a syntax error. Preprocessing directives (such as #include
) are not C++ statements and do not end with a semicolon.
Typically, output and input in C++ are accomplished with streams of data. When the preceding statement executes, it sends the stream of characters Welcome to C++!\n
to the standard output stream object (std::cout
), which is normally “connected” to the screen.
Indent the body of each function one level within the braces that delimit the function’s body. This makes a program’s functional structure stand out, making the program easier to read. Set a convention for the size of indent you prefer, then apply it uniformly. The tab key may be used to create indents, but tab stops may vary. We prefer three spaces per level of indent.
std
NamespaceThe std::
before cout
is required when we use names that we’ve brought into the program by preprocessing directives like #include <iostream>
. The notation std::cout
specifies that we are using a name, in this case cout
, that belongs to namespace std
. The names cin
(the standard input stream) and cerr
(the standard error stream)—introduced in Chapter 1—also belong to namespace std
. We discuss namespaces in Chapter 23, Other Topics. For now, you should simply remember to include std::
before each mention of cout
, cin
and cerr
in a program. This can be cumbersome—we’ll soon introduce using
declarations and the using
directive, which will enable you to omit std::
before each use of a name in the std
namespace.
In a cout
statement, the <<
operator is referred to as the stream insertion operator. When this program executes, the value to the operator’s right (the right operand) is inserted in the output stream. Notice that the <<
operator points toward where the data goes. A string’s characters normally display exactly as typed between the double quotes. However, the characters \n
are not displayed in Fig. 2.1’s sample output. The backslash (\
) is called an escape character. It indicates that a “special” character is to be output. When a backslash is encountered in a string, the next character is combined with the backslash to form an escape sequence. The escape sequence \n
means newline. It causes the cursor (i.e., the current screen-position indicator) to move to the beginning of the next line on the screen. Some common escape sequences are shown in the following table:
return
StatementLine 9
return 0; // indicate that program ended successfully
is one of several means we’ll use to exit a function. In this return
statement at the end of main
, the value 0
indicates that the program terminated successfully. If program execution reaches the end of main
without encountering a return
statement, C++ assumes that the program terminated successfully. So, we omit the return
statement at the end of main
in subsequent programs that terminate successfully.
The next two examples modify the program of Fig. 2.1. The first displays text on one line using multiple statements. The second displays text on several lines using one statement.
Figure 2.2 performs stream insertion in multiple statements (lines 7–8), yet produces the same output as Fig. 2.1. Each stream insertion resumes displaying where the previous one stopped. Line 7 displays Welcome
followed by a space, and because this string did not end with \n
, line 8 begins displaying on the same line immediately following the space.
Fig. 2.2 Displaying a line of text with multiple statements.
A single statement can display multiple lines by using additional newline characters, as in line 7 of Fig. 2.3. Each time the \n
(newline) escape sequence is encountered in the output stream, the screen cursor is positioned to the beginning of the next line. To get a blank line in your output, place two newline characters back to back, as in line 7.
Fig. 2.3 Displaying multiple lines of text with a single statement. (Part 1 of 2.)
Our next program obtains two integers typed by a user at the keyboard, computes their sum and outputs the result using std::cout
. Figure 2.4 shows the program and sample inputs and outputs. In the sample execution, the user’s input is in bold.
Fig. 2.4 Addition program that displays the sum of two integers.
Lines 8–10
int number1{0}; // first integer to add (initialized to 0) int number2{0}; // second integer to add (initialized to 0) int sum{0}; // sum of number1 and number2 (initialized to 0)
are declarations—number1
, number2
and sum
are the names of variables. These declarations specify that the variables number1
, number2
and sum
are data of type int
, meaning that these variables will hold integer (whole number) values, such as 7, –11, 0 and 31914. All variables must be declared with a name and a data type.
11 Lines 8–10 initialize each variable to 0
by placing a value in braces ({
and }
) immediately following the variable’s name—this is known as list initialization, which was introduced in C++11. Although it’s not always necessary to initialize every variable explicitly, doing so will help you avoid many kinds of problems.
Prior to C++11, lines 8–10 would have been written as:
int number1 = 0; // first integer to add (initialized to 0) int number2 = 0; // second integer to add (initialized to 0) int sum = 0; // sum of number1 and number2 (initialized to 0)
If you work with legacy C++ programs, you’re likely to encounter initialization statements using this older C++ coding style. In subsequent chapters, we’ll discuss various list initialization benefits.
Several variables of the same type may be declared in one declaration—for example, we could have declared and initialized all three variables in one declaration by using a comma-separated list as follows:
int number1{0}, number2{0}, sum{0};
But, this makes the program less readable and makes it awkward to provide comments that describe each variable’s purpose.
We’ll soon discuss the type double
for specifying real numbers and the type char
for specifying character data. Real numbers are numbers with decimal points, such as 3.4, 0.0 and –11.19. A char
variable may hold only a single lowercase letter, uppercase letter, digit or special character (e.g., $
or *
). Types such as int
, double
and char
are called fundamental types. Fundamental-type names consist of one or more keywords and must appear in all lowercase letters. For a complete list of C++ fundamental types and their typical ranges, see
https://en.cppreference.com/w/cpp/language/types
A variable name (such as number1
) is any valid identifier that is not a keyword. An identifier is a series of characters consisting of letters, digits and underscores (_
) that does not begin with a digit. C++ is case sensitive—uppercase and lowercase letters are different, so a1
and A1
are different identifiers.
C++ allows identifiers of any length, but some C++ implementations may restrict identifier lengths. Do not use identifiers that begin with underscores and double underscores, because C++ compilers use names like that for their own purposes internally.
Variable declarations can be placed almost anywhere in a program, but they must appear before the variables are used. For example, the declaration in line 8
int number1{0}; // first integer to add (initialized to 0)
could have been placed immediately before line 13
std::cin >> number1; // read first integer from user into number1
the declaration in line 9
int number2{0}; // second integer to add (initialized to 0)
could have been placed immediately before line 16
std::cin >> number2; // read second integer from user into number2
and the declaration in line 10
int sum{0}; // sum of number1 and number2 (initialized to 0)
could have been placed immediately before line 18
sum = number1 + number2; // add the numbers; store result in sum
In fact, lines 10 and 18 could have been combined into the following declaration and placed just before line 20:
int sum{number1 + number2}; // initialize sum with number1 + number2
Line 12
std::cout << "Enter first integer: "; // prompt user for data
displays Enter first integer:
followed by a space. This message is called a prompt because it directs the user to take a specific action. Line 13
std::cin >> number1; // read first integer from user into number1
uses the standard input stream object cin
(of namespace std
) and the stream extraction operator, >>
, to obtain a value from the keyboard.
When the preceding statement executes, the computer waits for the user to enter a value for variable number1
. The user responds by typing an integer (as characters), then pressing the Enter key (sometimes called the Return key) to send the characters to the computer. The computer converts the character representation of the number to an integer value and assigns this value to the variable number1
. Pressing Enter also causes the cursor to move to the beginning of the next line on the screen.
When your program is expecting the user to enter an integer, the user could enter alphabetic characters, special symbols (like # or @) or a number with a decimal point (like 73.5), among others. In these early programs, we assume that the user enters valid data. We’ll present various techniques for dealing with data-entry problems later.
Line 15
std::cout << "Enter second integer: "; // prompt user for data
displays Enter second integer:
on the screen, prompting the user to take action. Line 16
std::cin >> number2; // read second integer from user into number2
obtains a value for variable number2
from the user.
The assignment statement in line 18
sum = number1 + number2; // add the numbers; store result in sum
adds the values of variables number1
and number2
and assigns the result to variable sum
using the assignment operator =
. Most calculations are performed in assignment statements. The =
operator and the +
operator are binary operators because each has two operands. For the +
operator, the two operands are number1
and number2
. For the preceding =
operator, the two operands are sum
and the value of the expression number1 + number2
. Placing spaces on either side of a binary operator makes the operator stand out and makes the program more readable.
Line 20
std::cout << "Sum is " << sum << std::endl; // display sum; end line
displays the character string "Sum is"
followed by the numerical value of variable sum
followed by std::endl
—a stream manipulator. The name endl
is an abbreviation for “end line” and belongs to namespace std
. The std::endl
stream manipulator outputs a new-line, then “flushes the output buffer.” This simply means that, on some systems where outputs accumulate in the machine until there are enough to “make it worthwhile” to display them on the screen, std::endl
forces any accumulated outputs to be displayed at that moment. This can be important when the outputs are prompting the user for an action, such as entering data.
The preceding statement outputs multiple values of different types. The stream insertion operator “knows” how to output each type of data. Using multiple stream insertion operators (<<
) in a single statement is referred to as concatenating, chaining or cascading stream insertion operations.
Calculations can also be performed in output statements. We could have combined the statements in lines 18 and 20 into the statement
std::cout << "Sum is " << number1 + number2 << std::endl;
thus eliminating the need for the variable sum
.
The signature feature of C++ is that you can create your own data types called classes (we discuss this in Chapter 10 and explore it in depth in Chapter 11). You can then “teach” C++ how to input and output values of these new data types using the >>
and <<
operators, respectively. This is called operator overloading, which we explore in Chapter 14.
The following table summarizes the arithmetic operators:
Note the use of various special symbols not used in algebra. The asterisk (*
) indicates multiplication and the percent sign (%
) is the remainder operator, which we’ll discuss shortly. These arithmetic operators are all binary operators.
Integer division in which the numerator and the denominator are integers yields an integer quotient. For example, the expression 7/4
evaluates to 1
, and the expression 17 / 5
evaluates to 3
. Any fractional part in the result of integer division is truncated—no rounding occurs.
The remainder operator, %
, yields the remainder after integer division and can be used only with integer operands—x % y
yields the remainder after dividing x
by y
. Thus, 7%4
yields 3
and 17 % 5
yields 2
.
Parentheses are used in C++ expressions in the same manner as in algebraic expressions. For example, to multiply a
times the quantity b + c
we write a * (b + c)
.
C++ applies the operators in arithmetic expressions in a precise order determined by the following rules of operator precedence, which are generally the same as those in algebra:
1. Expressions in parentheses evaluate first. Parentheses are said to be at the “highest level of precedence.” In cases of nested or embedded parentheses, such as
(a * (b + c))
expressions in the innermost pair of parentheses evaluate first.
2. Multiplication, division and remainder operations evaluate next. If an expression contains several multiplication, division and remainder operations, they’re applied from left-to-right. These three operators are said to be on the same level of precedence.
3. Addition and subtraction operations evaluate last. If an expression contains several addition and subtraction operations, they’re applied from left-to-right. Addition and subtraction also have the same level of precedence.
Appendix A contains the complete operator precedence chart. Caution: If you have an expression such as (a + b) * (c - d)
in which two sets of parentheses are not nested, but appear “on the same level,” the C++ Standard does not specify the order in which these parenthesized subexpressions will evaluate.
When we say that C++ applies certain operators from left-to-right, we are referring to the operators’ grouping. For example, in the expression
a + b + c
the addition operators (+
) group from left-to-right as if we parenthesized the expression as (a+b)+ c
. Most C++ operators of the same precedence group left-to-right. We’ll see that some operators group right-to-left.
We now introduce C++’s if
statement, which allows a program to take alternative action based on whether a condition is true or false. Conditions in if
statements can be formed by using the relational operators and equality operators in the following table:
The relational operators all have the same level of precedence and group left-to-right. The equality operators both have the same level of precedence, which is lower than that of the relational operators, and group left-to-right.
Reversing the order of the pair of symbols in the operators !=
, >=
and <=
(by writing them as =!
, =>
and =<
, respectively) is normally a syntax error. In some cases, writing !=
as =!
will not be a syntax error, but almost certainly will be a logic error that has an effect at execution time. You’ll understand why when we cover logical operators in Chapter 4.
==
and =
Confusing the equality operator ==
with the assignment operator =
results in logic errors. We like to read the equality operator as “is equal to” or “double equals,” and the assignment operator as “gets” or “gets the value of” or “is assigned the value of.” As you’ll see in Section 4.12, confusing these operators may not necessarily cause an easy-to-recognize syntax error, but may cause subtle logic errors.
if
StatementFigure 2.5 uses six if
statements to compare two integers input by the user. If a given if
statement’s condition is true, the output statement in the body of that if
statement executes. If the condition is false, the output statement in the body does not execute.
Fig. 2.5 Comparing integers using if
statements, relational operators and equality operators. (Part 1 of 2.)
using
DeclarationsLines 6–8
using std::cout; // program uses cout using std::cin; // program uses cin using std::endl; // program uses endl
are using
declarations that eliminate the need to repeat the std::
prefix as we did in earlier programs. We can now write cout
instead of std::cout
, cin
instead of std::cin
and endl
instead of std::endl
, respectively, in the remainder of the program.
using
DirectiveIn place of lines 6–8, many programmers prefer the using
directive
using namespace std;
which, when you include a C++ standard library header (such as <iostream>
), enables your program to use any name from that header’s std
namespace. From this point forward in the book, we’ll use this directive in our programs.1
1. In Chapter 23, Other Topics, we’ll discuss some issues with using
directives in large-scale systems.
Lines 12–13
int number1{0}; // first integer to compare (initialized to 0) int number2{0}; // second integer to compare (initialized to 0)
declare the variables used in the program and initialize them to 0
.
Line 16
cin >> number1 >> number2; // read two integers from user
uses cascaded stream extraction operations to input two integers. Recall that we’re allowed to write cin
(instead of std::cin
) because of line 7. First, a value is read into number1
, then a value is read into number2
.
The if
statement in lines 18–20
if (number1 == number2) { cout << number1 << " == " << number2 << endl; }
determines whether the values of variables number1
and number2
are equal. If so, the cout
statement displays a line of text indicating that the numbers are equal. For each condition that is true
in the remaining if
statements starting in lines 22, 26, 30, 34 and 38, the corresponding cout
statement displays an appropriate line of text.
Each if
statement in Fig. 2.5 contains a single body statement that’s indented to enhance readability. Also, notice that we’ve enclosed each body statement in a pair of braces, { }
, creating what’s called a compound statement or a block.
You don’t need to use braces, { }
, around single-statement bodies, but you must include the braces around multiple-statement bodies. Forgetting to enclose multiple-statement bodies in braces leads to errors. To avoid errors, as a rule, always enclose an if
statement’s body statement(s) in braces.
Placing a semicolon immediately after the right parenthesis of the condition in an if
statement is often a logic error (although not a syntax error). The semicolon causes the body of the if
statement to be empty, so the if
statement performs no action, regardless of whether or not its condition is true. Worse yet, the original body statement of the if
statement now becomes a statement in sequence with the if
statement and always executes, often causing the program to produce incorrect results.
A lengthy statement may be spread over several lines. If a statement must be split across lines, choose meaningful breaking points, such as after a comma in a comma-separated list, or after an operator in a lengthy expression. If a statement is split across two or more lines, indent all subsequent lines and left-align the group of indented lines.
With the exception of the assignment operator =
, all the operators presented in this chapter group from left-to-right. Assignments (=
) group from right-to-left. So, an expression such as x = y = 0
evaluates as if it had been written x = (y = 0)
, which first assigns 0
to y
, then assigns the result of that assignment (that is, 0
) to x
.
Refer to the complete operator precedence chart in Appendix A when writing expressions containing many operators. Confirm that the operators in the expression are performed in the order you expect. If you’re uncertain about the order of evaluation in a complex expression, break the expression into smaller statements or use parentheses to force the order of evaluation, exactly as you’d do in an algebraic expression.
string
Throughout this book, we emphasize using preexisting valuable classes from the C++ standard library and various open-source libraries from the C++ open-source community. You’ll focus on knowing what libraries are out there, choosing the ones you’ll need for your applications, creating objects from existing library classes and making those objects exercise their capabilities. By Objects Natural, we mean that you’ll be able to program with powerful objects before you learn to create custom classes
You’ve already worked with C++ objects—specifically the cout
and cin
objects, which encapsulate the mechanisms for output and input, respectively. These objects were created for you behind the scenes using classes from the header <iostream>
. In this section, you’ll create and interact with objects of the C++ standard library’s string
2 class.
2. You’ll learn additional string
capabilities in subsequent chapters. Chapter 8 discusses class string
in detail, test-driving many more of its member functions.
string
Classes cannot execute by themselves. A Person
object can drive a Car
object by telling it what to do (go faster, go slower, turn left, turn right, etc.)—without knowing how the car’s internal mechanisms work. Similarly, the main
function can “drive” a string
object by calling its member functions—without knowing how the class is implemented. In this sense, main
in the following program is referred to as a driver program. Figure 2.6’s main
function test-drives several string
member functions.
Fig. 2.6 Standard Library string
class test program. (Part 1 of 2.)
Typically, you cannot call a member function of a class until you create an object of that class3—also called instantiating an object. Lines 8–10 create three string
objects:
• s1
is initialized with the string literal "happy"
,
• s2
is initialized with the string literal " birthday"
and
• s3
is initialized by default to the empty string
(that is, ""
).
3. You’ll see in Section 11.15 that you can call a class’s static
member functions without creating an object of that class.
When we declare int
variables, as we did earlier, the compiler knows what int
is—it’s a fundamental type that’s built into C++. In lines 8–10, however, the compiler does not know in advance what type string
is—it’s a class type from the C++ standard library.
When packaged properly, classes can be reused by other programmers. This is one of the most significant benefits of working with object-oriented programming languages like C++ that have rich libraries of powerful prebuilt classes. For example, you can reuse the C++ standard library’s classes in any program by including the appropriate headers—in this case, the <string>
header (line 4). The name string
, like the name cout
, belongs to namespace std
.
string
Member Function length
20 Lines 13–15 output each string
and its length. The string
class’s length
member function (new in C++20) returns the number of characters stored in a particular string
object. In line 13, the expression
s1.length()
returns s1
’s length by calling the object’s length
member function. To call this member function for a specific object, you specify the object’s name (s1
), followed by the dot operator (.
), then the member function name (length
) and a set of parentheses. Empty paren-theses indicate that length
does not require any additional information to perform its task. Soon, you’ll see that some member functions require additional information called arguments to perform their tasks.
From main
’s view, when the length
member function is called:
1. The program transfers execution from the call (line 13 in main
) to member function length
. Because length
was called via the s1
object, length
“knows” which object’s data to manipulate.
2. Next, member function length
performs its task—that is, it returns s1
’s length to line 13 where the function was called. The main
function does not know the details of how length
performs its task, just as the driver of a car doesn’t know the details of how engines, transmissions, steering mechanisms and brakes are implemented.
3. The cout
object displays the number of characters returned by member function length
, then the program continues executing, displaying the string
s s2
and s3
and their lengths.
string
Objects with the Equality OperatorsLike numbers, string
s can be compared with one another. Lines 18–20 show the results of comparing s2
to s1
using the equality operators—string
comparisons are case sensitive.4
4. In Chapter 8, you’ll see that strings perform lexicographical comparisons using the numerical values of the characters in each string.
Normally, when you output a condition’s value, C++ displays 0
for false or 1
for true. The stream manipulator boolalpha
(line 18) from the <iostream>
header tells the output stream to display condition values as the words false
or true
.
string
Member Function empty
Line 25 calls string
member function empty
, which returns true
if the string
is empty; otherwise, it returns false
. The object s3
was initialized by default to the empty string, so it is indeed empty, and the body of the if
statement will execute.
string
Concatenation and AssignmentLine 27 assigns a new value to s3
produced by “adding” the strings s1
and s2
using the + operator—this is known as string
concatenation. After the assignment, s3
contains the characters of s1
followed by the characters of s2
. Line 28 outputs s3
to demonstrate that the assignment worked correctly.
string
Member Functions starts_with
and ends_with
20 Lines 32–35 demonstrate new string
member functions starts_with
and ends_with
, which return true
if the string
starts with or ends with a specified substring, respectively; otherwise, they return false
. Lines 32 and 33 show that s1
starts with "ha"
, but s2
does not. Lines 34 and 35 show that s1
does not end with "ay"
but s2
does.
We presented many important basic features of C++ in this chapter, including displaying data on the screen, inputting data from the keyboard and declaring variables of fundamental types. In particular, you learned to use the output stream object cout
and the input stream object cin
to build simple interactive programs. We declared and initialized variables and used arithmetic operators to perform calculations. We discussed the order in which C++ applies operators (i.e., the rules of operator precedence), as well as the grouping of the operators. You saw how C++’s if
statement allows a program to make decisions. We introduced the equality and relational operators, which we used to form conditions in if
statements.
Finally, we introduced the notion of “objects natural” learning by creating objects of the C++ standard library class string
and interacting with them using equality operators and string
member functions. In subsequent chapters, you’ll create and use many objects of existing classes to accomplish significant tasks with minimal amounts of code. Then, in Chapters 10–14, you’ll create your own custom classes. You’ll see that C++ enables you to “craft valuable classes.” In the next chapter, we begin our introduction to control statements, which specify the order in which a program’s actions are performed.