← Back to C++ Course | Chapter 6: Arrays & Strings | Lesson 8 of 15

C++ std::string

What is std::string?

std::string, from the <string> header, is C++'s modern string type that handles its own memory allocation and resizing automatically, unlike a raw C-style char array which has a fixed size you must manage yourself. This automatic memory management eliminates an entire category of bugs around buffer overflows and manual sizing.

Example: What is std::string?

cpp
#include <iostream>
#include <string>

int main() {
	std::string name = "Alex"; // grows/shrinks automatically, no fixed buffer size
	std::cout << name << std::endl;
	return 0;
}

Declaring and Initializing

A std::string can be created empty (string s;), initialized directly from a literal (string s = "hello";), or built using a constructor that repeats a character a set number of times (string s(5, '*'); creates "*****"), giving you flexibility depending on what you're building.

Example: Declaring and Initializing

cpp
#include <iostream>
#include <string>

int main() {
	std::string a;
	std::string b = "hello";
	std::string c(5, 'x');
	std::cout << a << "|" << b << "|" << c << std::endl;
	return 0;
}

String Concatenation

The + and += operators let you join strings together dynamically, like string full = firstName + " " + lastName;, growing the resulting string's memory automatically as needed — something that would require careful manual buffer management with C-style strings.

Example: String Concatenation

cpp
#include <iostream>
#include <string>

int main() {
	std::string firstName = "Alex";
	std::string lastName = "Smith";
	std::string full = firstName + " " + lastName;
	std::cout << full << std::endl;
	return 0;
}

Reading Strings with cin

Just like with C-style strings, cin >> stops reading at the first whitespace character, so it can only capture a single word into a std::string. The global getline(cin, myString) function instead reads an entire line, spaces and all, which is almost always what you actually want when prompting a user for a full response.

Example: Reading Strings with cin

cpp
#include <iostream>
#include <string>

int main() {
	std::string name = "Alex"; // cin >> would stop at the first space
	std::cout << name << std::endl;
	return 0;
}

Accessing Characters

Individual characters can be accessed with [] the same way as an array, like name[0], but [] doesn't check whether the index is actually valid — .at(index) performs that same access with bounds checking, throwing an exception instead of silently reading invalid memory if the index is out of range.

Example: Accessing Characters

cpp
#include <iostream>
#include <string>

int main() {
	std::string name = "Alex";
	std::cout << name[0] << std::endl; // [] performs no bounds checking
	return 0;
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.