2.6 — Text (std::string)

📘 Chapter 2⏱ about 1 min read✍️ Beginner friendly
Read one box at a time. No rush.

std::string#

A std::string holds text: any number of characters. Use double quotes.

C++▶ Run
#include <iostream>#include <string> int main(){    std::string name { "Alex" };    std::cout << "Hello, " << name << "!\n";    return 0;}
Output
Hello, Alex!
Key idea

Remember #include <string> when you use std::string.

Joining strings#

Use + to stick strings together:

C++
std::string first { "Ice" };std::string second { "cream" };std::string food { first + " " + second };   // "Ice cream"

How long is it?#

C++
std::string word { "pizza" };std::cout << word.length();   // 5

Reading a whole line#

std::cin >> name stops at the first space. To read a full line (with spaces), use std::getline:

C++
std::string fullName {};std::cout << "Full name: ";std::getline(std::cin >> std::ws, fullName);std::cout << "Hi, " << fullName << '\n';
Why std::ws?

std::ws skips leftover spaces and new lines from earlier input. Without it, getline might read an empty line left over from a previous std::cin >>.

Many more string tools are in 8.5 — String tools.

Finished reading? Tick it off. Your progress is saved in this browser.

Tip: press ← / → to move between lessons, / to search.