capypad
0 day streak
cpp / beginner
Snippet

C-Style Strings: Working with Character Arrays

C-style strings are arrays of characters ending with a null character '\0'. They are different from C++ std::string but still widely used. You can use functions from <cstring> like strlen(), strcpy(), and strcmp() to manipulate them.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <cstring>
 
int main() {
char greeting[] = "Hello";
char name[20];
 
std::cout << "Enter your name: ";
std::cin.getline(name, 20);
 
std::cout << greeting << ", " << name << "!" << std::endl;
std::cout << "Length: " << strlen(name) << std::endl;
 
return 0;
}
Breakdown
1
#include <iostream>
Header for input/output operations
2
#include <cstring>
Header for C-string manipulation functions
3
char greeting[] = "Hello";
Character array initialized with a string literal
4
char name[20];
Declares space for up to 19 characters plus null terminator
5
std::cin.getline(name, 20);
Reads a full line including spaces into the name array
6
strlen(name)
Returns the length of the string without the null terminator