C++ PROGRAMMING ยท 14 MIN STUDY

Text with std::string

Store, read, join, inspect, and modify text using the C++ standard-library string type.

Learning objectives

  • Distinguish a character from a string.
  • Create and modify std::string objects.
  • Read a complete line with std::getline.
  • Use common string operations safely.

Prerequisites: variables, input/output, and the idea that a type determines which operations are available. Examples use C++17 syntax.

Character versus text

A char represents one character value, commonly written with single quotes: 'A'. A string represents a sequence of characters and is written with double quotes: "OpenLearn". For everyday text, C++ programmers usually use std::string.

Create a string

C++17
#include <iostream>
#include <string>

int main() {
    std::string name{"Asha"};
    std::string course{"C++"};
    std::cout << name << " is learning " << course << '\n';
}

#include <string> provides the standard string type. The name std::string includes the std namespace because it is part of the C++ standard library.

Read one word or a whole line?

Formatted extraction with std::cin >> name reads a token and stops at whitespace. To read a full line that may contain spaces, use std::getline.

C++17
std::string full_name;
std::cout << "Enter your full name: ";
std::getline(std::cin, full_name);
std::cout << "Hello, " << full_name << '\n';

If a previous std::cin >> number operation left the newline in the input stream, the next getline may read that remaining newline and return an empty line. In that situation, discard the rest of the current line deliberately, often with std::getline(std::cin, ignored), before reading the next full line. Do not add this workaround blindly when no earlier formatted input occurred.

Useful operations

ExpressionMeaning
text.size()Number of char elements in the string
text.empty()Whether the string has no characters
text += "!"Append characters
text[0]Access the first character when the string is non-empty
text.find("C++")Find a substring; returns std::string::npos when absent
text.substr(0, 3)Create a substring from a position and length

Small example: clean a label

std::string label{"OpenLearn"};
label += " Engineering";
std::cout << label << '\n';
std::cout << "characters: " << label.size() << '\n';

Appending changes the string object. size() reports the number of stored char elements, not necessarily the number of user-perceived characters in every Unicode text. Unicode graphemes can use multiple code units.

Indexes and bounds

String indexes start at zero. For a string with n characters, valid indexes are from 0 through n - 1. Check that a string is not empty before reading text[0]. The at() member function performs bounds checking and throws std::out_of_range for an invalid position.

Common mistakes

  • Using single quotes for a multi-character string.
  • Expecting cin >> text to keep spaces.
  • Accessing index zero when the string is empty.
  • Assuming size() always counts visible human characters in Unicode text.
  • Comparing find() with zero instead of checking against std::string::npos.

Practice

  1. Read a full name with getline and print a greeting.
  2. Append your branch name to a course title and print the resulting length.
  3. Search for the word code and correctly report whether it exists.
  4. Write a program that checks empty() before printing the first character.

Check your understanding

Why does cin >> name stop at a space?

Answer: Formatted string extraction reads one whitespace-delimited token. Use getline to read the rest of a line including spaces.

Practice solutions

Show worked solutions
  1. Declare std::string full_name;, call std::getline(std::cin, full_name);, then print the greeting. Include <iostream> and <string>.
  2. Append with course += " - " + branch;, then print course.size(). The result counts stored char elements.
  3. Use const auto position = text.find("code"); and test position != std::string::npos. Do not test the result as a Boolean because a match at position zero is valid.
  4. Use if (!text.empty()) before reading text[0] or text.front(); otherwise print a message that the string is empty.

Summary

Use std::string for ordinary text, getline for complete input lines, and check bounds before indexing. Remember that string size counts stored character elements, not necessarily visible Unicode symbols.

References