In C++, the <string> library provides a modern, safe, and powerful way to handle text. Unlike old C-style character arrays, the std::string class automatically manages memory, meaning you don't have to worry about specifying the exact size of your text beforehand.
You can easily concatenate (join), measure, and manipulate strings using built-in methods.
#include <iostream> #include <string> using namespace std;int main() { string firstName = "John "; string lastName = "Doe";
// Concatenation string fullName = firstName + lastName;
cout << "Name: " << fullName << "\n";
// Getting the length of the string cout << "Length: " << fullName.length() << " characters\n";
return 0; }
While std::string is much safer than raw character arrays, beginners still encounter a few common errors.
You can access individual characters in a string using square brackets, like fullName[0]. However, if the string has a length of 5, and you try to access fullName[10], C++ will not stop you! It will access raw, unallocated memory, leading to unpredictable behavior.
The Fix: Use the .at() method (e.g., fullName.at(10)), which throws an out_of_range error safely, preventing silent memory corruption.
You can add a std::string variable and a literal together: string a = myStr + " test";. However, you cannot add two raw text literals together directly using the + operator!
Code like string a = "Hello " + "World"; will result in a compiler error because C++ treats raw "text" as old C-style arrays, not std::string objects.
If you use cin >> myString; and the user types "John Doe", cin stops reading at the first space. myString will only contain "John".
The Fix: Use the getline() function to read a full line: getline(cin, myString);
Which method safely accesses a character in a string and checks if the index is valid?