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::stringobjects. - 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
#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.
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
| Expression | Meaning |
|---|---|
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 >> textto 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 againststd::string::npos.
Practice
- Read a full name with
getlineand print a greeting. - Append your branch name to a course title and print the resulting length.
- Search for the word
codeand correctly report whether it exists. - 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
- Declare
std::string full_name;, callstd::getline(std::cin, full_name);, then print the greeting. Include<iostream>and<string>. - Append with
course += " - " + branch;, then printcourse.size(). The result counts storedcharelements. - Use
const auto position = text.find("code");and testposition != std::string::npos. Do not test the result as a Boolean because a match at position zero is valid. - Use
if (!text.empty())before readingtext[0]ortext.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.