7.2. string variables¶
You can create a variable with type string in the usual ways.
In the code below, 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.
std::string first;
first = "Hello, ";
std::string second = "world.";
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 << '\n';
In order to compile this code, you will have to include the header file
containing the string definitions to all your source files
that refer to the string type.
Run the active code below!
1#include <iostream>
2#include <string>
3
4int main() {
5 std::string first;
6 first = "Hello, ";
7 std::string second = "world.";
8 std::cout << first << second << '\n';
9}
Q1
Construct a block of code that correctly prints out a string variable.
-
std::cout << x << '\n'; -
std::string x; -
x = "It is cold outside!"; -
x = "It is cold outside"
Q2
How would you initialize a string?
Q3
Click on each spot where a string assignment occurs.
}Remember, assignment and initialization are different.
Remember, assignment and initialization are different.
Correct.
Correct.
Remember, assignment and initialization are different.
Correct.