Chapter 8: Arrays & Strings
Arrays & Strings in C++: Storing Collections of Data Like a Pro!
Hello my amazing student! π Welcome to Lesson 8 β Arrays & Strings! This is a huge step forward because almost every real program needs to handle multiple pieces of data at once: list of students, scores, names, characters in a sentence, pixels in an image, etc.
Today weβll cover everything you need to know as a beginner-to-intermediate C++ programmer:
- C-style fixed-size arrays (the old-school way β still very important!)
- std::array (modern, safe C++11+ replacement)
- std::string (the powerful, easy-to-use string class)
- std::string_view (C++17+ lightweight view β super useful and efficient!)
Weβll go very slowly, with tons of examples, real-life analogies, common mistakes, best practices, and complete programs you can run right away.
Letβs start!
1. C-style Fixed-Size Arrays (The Classic Way)
These are the original arrays from C β still used everywhere in C++.
Syntax:
|
0 1 2 3 4 5 6 7 |
type name[size]; // declaration type name[size] = {values}; // declaration + initialization |
Key points:
- Size must be known at compile time (or constexpr)
- Size is fixed β you cannot change it later
- Indices start at 0
- No built-in safety β going out of bounds causes undefined behavior (very dangerous!)
Simple example:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
#include <iostream> int main() { // Array of 5 integers int scores[5] = {85, 92, 78, 95, 88}; // Access elements std::cout << "First score: " << scores[0] << "\n"; // 85 std::cout << "Last score: " << scores[4] << "\n"; // 88 // Change value scores[2] = 100; std::cout << "After update: " << scores[2] << "\n"; // 100 // Loop through array (classic way) std::cout << "All scores: "; for (int i = 0; i < 5; ++i) { std::cout << scores[i] << " "; } std::cout << "\n"; return 0; } |
Dangerous mistake β out of bounds:
|
0 1 2 3 4 5 6 7 |
int arr[3] = {1, 2, 3}; std::cout << arr[5]; // β UNDEFINED BEHAVIOR! (crash, wrong value, anything can happen) |
Pro tip: Always keep track of the size yourself β common pattern:
|
0 1 2 3 4 5 6 7 8 9 |
const int SIZE = 5; int numbers[SIZE] = {10, 20, 30, 40, 50}; for (int i = 0; i < SIZE; ++i) { ... } |
Modern alternative: Use std::array (next section) β it remembers its size!
2. std::array β The Modern, Safe C++ Array (C++11+)
std::array is a fixed-size array with all the safety and convenience of the STL.
Advantages over C-style:
- Knows its own size (size() member function)
- Has .at() which checks bounds (throws exception if out of range)
- Can be passed to functions easily
- Works with range-based for loops perfectly
Include: #include <array>
Example β Everything you need:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
#include <iostream> #include <array> int main() { // Modern array of 5 integers std::array<int, 5> scores = {85, 92, 78, 95, 88}; // Size is known! std::cout << "Number of scores: " << scores.size() << "\n"; // 5 // Safe access with .at() β throws if out of bounds std::cout << "Score at index 2: " << scores.at(2) << "\n"; // 78 // scores.at(10); // β throws std::out_of_range exception! // Range-based for loop (beautiful!) std::cout << "All scores: "; for (int score : scores) { std::cout << score << " "; } std::cout << "\n"; // Change value scores[1] = 99; std::cout << "After update: " << scores[1] << "\n"; // Initialize with same value std::array<int, 10> zeros{}; // all 0 // or std::array<int, 10> zeros = {}; return 0; } |
Best practice (2025+): Whenever you need a fixed-size collection β prefer std::array over C-style arrays!
3. std::string β The Easy & Powerful String Class
std::string is the go-to way to handle text in modern C++.
Include: #include <string>
Key features:
- Can grow or shrink automatically
- Very easy to use (+, +=, size(), empty(), find(), substr(), etc.)
- Safe β no buffer overflows like in C
Basic examples:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
#include <iostream> #include <string> int main() { // Creation std::string name = "Webliance"; std::string greeting = "Hello, "; // Concatenation std::string full = greeting + name + "!"; std::cout << full << "\n"; // Hello, Webliance! // Append full += " Welcome to C++!"; std::cout << full << "\n"; // Length & access std::cout << "Length: " << full.size() << "\n"; // or full.length() std::cout << "First char: " << full[0] << "\n"; // H std::cout << "Last char: " << full.back() << "\n"; // ! // Safe access std::cout << full.at(7) << "\n"; // throws if out of range // Comparison if (name == "Webliance") { std::cout << "Correct name!\n"; } // Input with spaces std::string fullName; std::cout << "Enter your full name: "; std::getline(std::cin, fullName); std::cout << "Nice to meet you, " << fullName << "!\n"; return 0; } |
Very useful string methods:
| Method | What it does | Example |
|---|---|---|
| size() / length() | Number of characters | name.size() |
| empty() | Is string empty? | if (s.empty()) … |
| clear() | Empty the string | s.clear(); |
| find(“text”) | Find position of substring (or npos) | if (s.find(“C++”) != std::string::npos) |
| substr(pos, len) | Extract substring | s.substr(0, 5) β first 5 chars |
| +=, + | Concatenate | s += ” world!”; |
4. std::string_view β Lightweight Read-Only View (C++17+)
std::string_view is a non-owning view into a string (or char array).
Why itβs awesome:
- Zero copy β very fast & memory efficient
- Works with any contiguous sequence of characters
- Cannot modify the data (read-only)
- Perfect for function parameters when you just want to read a string
Include: #include <string_view>
Example β Best practice for function parameters:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
#include <iostream> #include <string> #include <string_view> void printName(std::string_view name) { // β No copy! std::cout << "Hello, " << name << "!\n"; // name[0] = 'A'; // ERROR β string_view is read-only } int main() { std::string s = "Webliance"; const char* cstr = "Alice"; printName(s); // works printName(cstr); // works printName("Bob"); // works printName(std::string_view("Charlie", 7)); // works return 0; } |
Modern recommendation (2025+):
- When a function only reads a string β use std::string_view
- When it needs to own or modify the string β use std::string
5. Full Practical Example β Student Names & Scores
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
#include <iostream> #include <array> #include <string> #include <iomanip> int main() { // Modern fixed-size array std::array<std::string, 4> names = {"Alice", "Bob", "Charlie", "Diana"}; std::array<double, 4> scores{}; std::cout << "Enter scores for 4 students:\n"; for (size_t i = 0; i < names.size(); ++i) { std::cout << names[i] << ": "; std::cin >> scores[i]; } // Beautiful output std::cout << "\n=== Student Results ===\n"; std::cout << std::left << std::setw(15) << "Name" << std::setw(10) << "Score" << "\n"; for (size_t i = 0; i < names.size(); ++i) { std::cout << std::setw(15) << names[i] << std::fixed << std::setprecision(1) << scores[i] << "\n"; } return 0; } |
Your Mini Homework (Try These!)
- Create a C-style array of 6 integers, fill it with numbers 1 to 6, and print them in reverse order.
- Use std::array<double, 5> to store temperatures, calculate average using range-based for.
- Write a function that takes std::string_view and prints whether the string contains “C++”.
- Ask the user for their full name using std::getline, then print:
- Length
- First name (before space)
- Last name (after space)
Youβre doing incredibly well! You now know how to handle lists of numbers and text β the foundation of almost every real application!
Next lesson: Pointers & References β the gateway to dynamic memory and advanced C++!
Any questions? Confused about std::array vs C-style? Want more string tricks or string_view examples? Just ask β your friendly C++ teacher is always here for you! π
