In C++, std::string::pop_back() removes the last character.
The string must not be empty. Include <string>. (C++11)
This is a member of std::string. A string grows as you append, stores characters contiguously, and can reallocate—after growth, old iterators and references may be invalid. Prefer at() when you want bounds checks; remember find returns npos when missing.
Syntax
Call on a non-empty string.
C++
s.pop_back();
Call
What it does
s.pop_back()
Erase the last character.
Check !s.empty() before calling.
Library declarations
C++
void pop_back();
Parameters
Parameter
Description
None
pop_back() takes no parameters. Call it with empty brackets.
Return Value
Return Value
Description
void
No return value.
C++ Examples
Example 1 — Basic pop_back()
Drop the last character.
C++
#include <iostream>
#include <string>
int main() {
std::string s = "cat!";
s.pop_back();
std::cout << s << '\n';
return 0;
}
Output
cat
How It Works
The last character is '!'.
pop_back() removes it.
Left with "cat".
Example 2 — Pop While Condition
Remove trailing spaces.
C++
#include <iostream>
#include <string>
int main() {
std::string s = "hi ";
while (!s.empty() && s.back() == ' ') {
s.pop_back();
}
std::cout << '[' << s << "]\\n";
return 0;
}
Output
[hi]
How It Works
We loop while the last character is a space.
Each pop_back shortens the string.
Trailing spaces are gone.
Example 3 — Safe Pop
Only pop when not empty.
C++
#include <iostream>
#include <string>
int main() {
std::string s;
if (!s.empty()) {
s.pop_back();
} else {
std::cout << "nothing to pop\\n";
}
return 0;
}
Output
nothing to pop
How It Works
The string is empty.
We skip pop_back to avoid undefined behavior.
A message explains the situation.
Frequently Asked Questions
It removes the last character of a non-empty string.
Undefined behavior. Check empty() first.
No. Read back() first if you need the value, then pop_back().