Skip to main content

How To Think Like a Computer Scientist C++ Edition The Pretext Interactive Version

Section 7.2 string variables

You can create a variable with type string in the usual ways.
Listing 7.2.1. In this active code, the first line creates a string without giving it a value. The second line assigns it the string value "Hello,". The third line is a combined declaration and assignment, also called an initialization.
Normally when string values like "Hello, " or "world." appear, they are treated as C strings. In this case, when we assign them to an string variable, they are converted automatically to string values.
We can output strings in the usual way:
cout << first << second << endl;

Note 7.2.1.

In order to compile this code, you will have to include the header file for the string class. If you are already including iostream, you may get away with not explicitly including string. In some environments, iostream will include string for you. But it is best to explicitly include string if your code relies on it.
Listing 7.2.2. Run this active code!

Checkpoint 7.2.1.

Construct a block of code that correctly prints out a string variable.

Checkpoint 7.2.2.

How would you initialize a string?
  • string x = "Hello";
  • This is the correct way to initialize a string.
  • x = "Hello";
  • This is an assignment.
  • string x;
  • This is a declaration.

Checkpoint 7.2.3.

You have attempted 1 of 6 activities on this page.