CodeBlanks Logo Icon CodeBlanks

std::string basics

Learn to create and initialize std::string.

std::string basics

In C++, text is represented by the std::string type. To create a string you wrap the text in double quotes ("): std::string city = "Paris";. Single quotes are only for a single character (char).

To use std::string you must include the #include <string> header. You can assign a new value to a string variable later: city = "Lyon"; drops the old value and stores the new one. Everything between the double quotes is taken literally, which is why numbers stay unquoted and text stays inside quotes.

Escape sequences

Some characters cannot be placed directly inside double quotes: a new line, a tab, or the double quote itself. For these you use an escape sequence. A backslash (\) followed by a character gives it a special meaning.

\n is a new line, \t is a tab, \\ is a backslash, \" is a double quote. For example, "Line one\nLine two" prints across two lines. With std::cout, \n moves the cursor to the next line.

Practice Print the city variable

Declare a city variable and set its value to "Paris". Then print city with std::cout. Use double quotes.

Starter code

main.cpp
#include <iostream>
#include <string>

int main() {
    // Write the city variable here
    return 0;
}

Sample solution

main.cpp
#include <iostream>
#include <string>

int main() {
    std::string city = "Paris";
    std::cout << city << std::endl;
    return 0;
}

Expected output

Paris

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which is a valid std::string declaration?

main.cpp
std::string name = ...;
  • std::string name = 'Alex';
  • std::string name = Alex;
  • std::string name = "Alex"; Correct answer
  • std::string name = "Alex;

Explanation: Double quotes declare a std::string.

2 Write the newline escape sequence

Question
std::string line = "Line one____Line two";
Answer
std::string line = "Line one\nLine two";

Explanation: \n is the newline character.

3 Match each escape sequence to its meaning

Term Meaning
\n New line
\t Tab
\\ Backslash
\" Double quote

All lessons in Beginner