Chapter 1
Working with strings
Objectives
• Understand simple programs using character strings and the string library.
• Get acquainted with declarations, variables and initialization.
• Understand basic stream input using the input operator.
• Get an understanding of some issues related to input and output buffers.
C++
• Within C++, there is a much smaller and cleaner language struggling to get out.
– Bjarne Stroustrup
Greeting
#include <iostream>
#include <string>
int main()
{
std::cout << "Please enter your first name: ";
std::string name; // define name
std::cin >> name; // read into name
std::cout << "Hello, " << name << "!" << std::endl;
system(“pause”);
return 0;
}
Missing std::endl
• Notice that the initial output statement does not end with std::endl.
• This is because we want the input later on in the program to occur at the end of this line.
Variables
• Unlike some languages (like Python) C++ is typed.• In order to store a value we must explicitly create
a variable.• Technically, a variable is an object that has a
name.• An object is a part of the computer’s memory that
has a type.• The type of an object determines how it can be
used (its interface) and how much memory must be reserved.
std::string
• Our program asks for a person’s name which is represented by a string of characters.
• The type for storing a string of characters (std::string) is not included in the core language.
• We must include the appropriate header file.#include<string>
std::string
• To create a space in memory to store the string input we define a variable.
std::string name;• This reserves memory to store a string and
associates it with the label name.• This is a local variable and will be
destroyed when we reach the end of the block } where it is defined.
Initialization
• When the string is created, it is initialized to a starting value.
• The programmer can specify the initialization value.
• If this is not done, the string is initialized to be an empty or null string.
Stream Input
• Stream input is similar to stream output except that the input operator >> is used with the stream std::cin.
• This extracts information from the input stream and stores it in the specified variable.
• When the characters are extracted, leading white space characters (space, tab, backspace, end of line) are removed and characters are extracted up to the first white space encountered after that – the input operator only reads one “word” at a time.
Stream Input
• Suppose the input is “ Hello, world!”• The line std::cin >> name would store
“Hello,” in the string.• The remaining characters (“ world!”) are
still there to be read.• Both words could be read by chaining more
than one input operator.std::cin >> first >> last;
Buffers
• It is often more efficient for the computer to store up input and output operations in buffers and do many of them all at once (called flushing the buffer).
• This can lead to odd behavior.– Output may not occur at the instant the output
statement is encountered.– If the input buffer is not empty, additional
(unexpected) characters may be in read.
Buffers
• This odd behavior shows up in two places in our program.– The prompt “Please enter your first name: “
doesn’t appear on the screen when the program encounters the output statement. It actually appears at the input statement.
– When the input occurs the white space at the end (end of line character) remains in the input buffer. It will be read (or ignored) by the next input.
Flushing the Output Buffer
• If we have a program with output but no input we may need to force the output buffer to flush in order to give information to the user.
• Three events flush the output buffer.– The buffer gets full.– Input is requested from the input stream.– The programmer flushes the buffer.
• Flushing the buffer, when necessary, is a good habit to get into.
Framed Greeting
• Suppose we want a more exciting greeting.********************* ** Hello, Melissa ! ** *********************
Framed Greeting
• We will build up each line as a string and then print it.
• First, we input the name as before.• Next, we create a string which will contain
the greeting we want to frame.const std::string greeting = "Hello, " + name + "!";
Creating Greeting
const std::string greeting = "Hello, " + name + "!";
• greeting is initialized when it is created.• The + operator is used to concatenate
std::string variables.– The + operator is overloaded so that it will do
one thing when use with numbers and another when used with strings.
+ and Conversions
const std::string greeting = "Hello, " + name + "!”;
• The + operator also converts the string literal "Hello, " into a std::string.– It knows to do this automatic converssion
because one of the objects is already a std::string.
– It is not legal to concatenate two string literals.
+ is Left Associative
const std::string greeting = "Hello, " + name + "!";
• There are two + operators in the expressions. Which one gets done first?– The one on the left is done first because + is left
associative.– Operators can be either left or right associative.
= is Right Associative
• We can see right associativity with the = operator.
• Notice the operation on the right is performed first.
Expressionx = y = 3
x = (y = 3)x = 3
Side Effect
y = 3x = 3
const Variables
const std::string greeting = "Hello, " + name + "!”;
• const is used in the variable definition. This means greeting cannot be changed later.
• Why make a variable that cannot be changed?– It protects us from accidentally changing it later.– This is an example of the concept of least
privilege. If something shouldn’t happen, make it so it can’t happen.
Strings as Objects
• To create the lines above and below the greeting we initialize the strings in a different way.
• Strings are objects and as such they have member functions (methods).
• Two of these methods are– A constructor.– size() that returns the length of the string.
Building the Frame
• The second and fourth lines are created using the following.
const std::string spaces(greeting.size(), ' ');
• The syntax for creating an object by invoking its constructor is a little different in C++ than it is in Python, but the idea is the same.
• The constructor for the string class can accept a number and a character and will then create a string with the character repeated the specified number of times.
Building the Frame
• Next the ‘*’ characters are added.const std::string second = "* " + spaces + " *";
• The first and last lines are created in a similar manner.
const std::string first(second.size(), '*');
• Finally all the strings are printed in the appropriate order.
Building the Frame
std::cout << std::endl;
std::cout << first << std::endl;
std::cout << second << std::endl;
std::cout << "* " << greeting << " *" << std::endl;
std::cout << second << std::endl;
std::cout << first << std::endl;
Framed Greeting
• Putting this all together we get the completed program.#include <iostream>
#include <string>
int main()
{
std::cout << "Please enter your first name: ";
std::string name;
std::cin >> name;
const std::string greeting = "Hello, " + name + "!";
const std::string spaces(greeting.size(), ' ');
const std::string second = "* " + spaces + " *";
const std::string first(second.size(), '*');
Framed Greeting
std::cout << std::endl;
std::cout << first << std::endl;
std::cout << second << std::endl;
std::cout << "* " << greeting << " *" << std::endl;
std::cout << second << std::endl;
std::cout << first << std::endl;
system(“pause”);
return 0;
}
Homework Chapter 1 (page 15)
• Hint, errors can be subtle. Type these in and see what happens. (25 pts total possible)– 1-0– 1-1 (paper, 5 pts)– 1-2 (paper, 5 pts)– 1-3 (paper, 5 pts)– 1-4 (paper, 5 pts)– 1-5 (paper, 5 pts)– 1-6 (paper, 5 pts)