Learn about strings in C++ programming, including C-style strings (character arrays) and the C++ string class, with examples and common operations.
string
class (from <string>
library)\0
).
char name[] = "John";
initializes a character array.\0
is automatically added at the end.J | o | h | n | \0 |
---|
\0
tells C++ where the string ends.
string
Class (Modern Approach)string
class from the <string>
library, which is more flexible and powerful.
string name;
declares a string variable.cin >> name;
takes input (but stops at space).cout << name;
prints the string.string
as a dynamic notebook where you can write, erase, and modify text freely.
Feature | C-Style Strings (char[] ) | std::string (C++ Strings) |
---|---|---|
Null-Termination | Yes (\0 is required) | No (\0 is managed internally) |
Memory Management | Manual (fixed size) | Dynamic (auto-resizes) |
Safer? | ❌ Prone to buffer overflows | ✅ Safer and more convenient |
Functionality | Limited (needs <cstring> ) | Rich methods (length, find, substr, etc.) |
std::string
over C-style strings unless you have a specific reason to use character arrays (e.g., low-level memory manipulation, embedded systems).
getline
)getline()
.
getline()
?cin
only takes a single word, but getline(cin, variable);
reads the whole line, including spaces.
+
operator joins strings." "
adds a space between first and last names.Error | Cause | Solution |
---|---|---|
cin skips input | getline() follows cin | Use cin.ignore() before getline() |
String out of bounds | Accessing invalid index | Ensure index is within 0 to str.length()-1 |
Concatenation error | Using + with char[] | Use string class instead of char[] |
\0
termination.string
class is modern and easy to use.getline()
handles multi-word input.