C++ · Beginner level

Beginner level · Module 3: Vectors, Arrays and Strings · Lesson 2 of 3

Working with std::string

Read, join, search and split text with std::string and handle whole lines of input.

In this lesson you will

  • Use common std::string operations
  • Read lines with std::getline and split them with std::istringstream

Key concepts

std::stringgetlinefind and substrstd::istringstream

The lesson

std::string manages its own memory and grows as needed. Join text with +, compare with ==, get the length with size(), and access characters with [] or at(). find returns the position of a substring, or std::string::npos if it is absent; substr(pos, len) extracts part of a string.

std::cin >> word stops at whitespace. To read a full name or a line from a file, use std::getline(std::cin, line). Mixing >> and getline leaves a newline behind; call std::cin.ignore() after >> before using getline.

std::istringstream turns a string into a stream, so you can read words or numbers from it with >> — a simple way to split a line such as "Akol 72" into a name and a mark.

Step by step

  1. Read a full name with getline and print its length.
  2. Find the first space and split the name into first and last name.
  3. Parse "Akol 72" with std::istringstream.
  4. Convert a word to uppercase with a loop and std::toupper.

Practice activity

Write a program that reads lines like "Mary Ladu 68" and prints "LADU, Mary — 68".

Expected result: Each line is reformatted correctly, including names of different lengths.

Check your understanding

  1. What does find return when the text is not found?

    Show answer

    std::string::npos.

  2. Why use std::getline instead of >> for names?

    Show answer

    >> stops at the first space, while getline reads the whole line.

Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.