C++: C-Style Strings

Last updated: 2026-08-26

C++ has two types of strings:

  1. C-style strings (character arrays)
  2. C++ string (covered later)

This lesson covers C-style strings first — they are a legacy from C that C++ maintains for compatibility. Understanding them helps you grasp the underlying principles of strings.



1. What is a C-Style String?

(1) 1.1 Essence: Character Array + Null Terminator

A C-style string is simply a character array, with one special rule:

TEXT 📖 Display only
"Hello" in memory:
+---+---+---+---+---+----+
| H | e | l | l | o | \0 |
+---+---+---+---+---+----+
 0 1 2 3 4 5 ← indices

💡 Key point: The length of a C-style string is 5 (Hello), but the array size must be at least 6 (to store \0).



2. Declaration and Initialization

(1) 2.1 Declaring a C-Style String

Syntax:

TEXT 📖 Display only
char stringName[Size];

Example:

▶ Example 2: Basic Programming Practice (Difficulty ⭐)

CPP
#include <iostream>

int main() {
 char name[20]; // Can store 19 chars + 1 \0
 
 name[0] = 'H';
 name[1] = 'e';
 name[2] = 'l';
 name[3] = 'l';
 name[4] = 'o';
 name[5] = '\0'; // Don't forget the null terminator!
 
 std::cout << "Name: " << name << std::endl; // Hello
 
 return 0;
}
▶ Try it Yourself

Output:

TEXT 📖 Display only
Name: Hello

💡 Tip: Manually adding \0 is tedious — you'll learn simpler methods later.

(2) 2.2 Initializing a C-Style String

Method 1: Initialize with a string literal

CPP
#include <iostream>

int main() {
 char name = "Hello"; // ✅ Compiler auto-adds \0, array size is 6
 
 std::cout << "Name: " << name << std::endl;
 
 return 0;
}

💡 Key point: When initializing with a string literal, you don't need to specify the array size — the compiler calculates it automatically (including \0).



3. Common String Functions

C-style string functions are in the cstring header file.

(1) 3.1 strlen: Calculate String Length

TEXT 📖 Display only
#include <iostream>
#include <cstring> // Must include this header

int main() {
 char name = "Hello";
 
 std::cout << "String: " << name << std::endl;
 std::cout << "Length: " << std::strlen(name) << std::endl; // 5(excluding \0)
 
 return 0;
}

💡 Tip: std::strlen returns the number of effective characters (excluding \0), while sizeof returns the array size (including \0).

CPP
char name = "Hello";
std::cout << sizeof(name) << std::endl; // 6(Array size)
std::cout << std::strlen(name) << std::endl; // 5(effective character count)

(2) 3.2 strcpy: Copy a String

TEXT 📖 Display only
#include <iostream>
#include <cstring>

int main() {
 char src = "Hello";
 char dest[20];
 
 std::strcpy(dest, src); // Copy src to dest
 
 std::cout << "src:" << src << std::endl;
 std::cout << "dest:" << dest << std::endl;
 
 return 0;
}

⚠️ Warning: std::strcpy does not check the destination array's size — if dest is too small, it will cause a buffer overflow!

Safer function (after C++11):

CPP
std::strncpy(dest, src, sizeof(dest) - 1); // Copy at most sizeof(dest)-1 characters
dest[sizeof(dest) - 1] = '\0'; // Manually add null terminator

(3) 3.3 strcat: Concatenate Strings

TEXT 📖 Display only
#include <iostream>
#include <cstring>

int main() {
 char greeting[50] = "Hello, ";
 char name = "World";
 
 std::strcat(greeting, name); // Append name to greeting
 
 std::cout << greeting << std::endl; // Hello, World
 
 return 0;
}

(4) 3.4 strcmp: Compare Strings

CPP
#include <iostream>
#include <cstring>

int main() {
 char str1 = "Hello";
 char str2 = "Hello";
 char str3 = "World";
 
 std::cout << "strcmp(str1, str2) = " << std::strcmp(str1, str2) << std::endl;
 std::cout << "strcmp(str1, str3) = " << std::strcmp(str1, str3) << std::endl;
 
 return 0;
}

Return values:

💡 Tip: Don't use == to compare C-style strings! == compares addresses, not content.

TEXT 📖 Display only
char str1 = "Hello";
char str2 = "Hello";

if (str1 == str2) { // ❌ Error: Comparing addresses, not content
 // ...
}

if (std::strcmp(str1, str2) == 0) { // ✅ Correct:Use strcmp to compare content
 // ...
}


4. Handling C-Style Strings with cin and cout

(1) 4.1 Reading Strings

CPP
#include <iostream>

int main() {
 char name[20];
 
 std::cout << "Please enter your name: ";
 std::cin >> name; // ✅ Can read strings (but no spaces)
 
 std::cout << "Hello," << name << "!" << std::endl;
 
 return 0;
}

💡 Problem: cin >> stops at whitespace! If you enter "John Smith", it only reads "John".

Solution: Use std::cin.getline

CPP
#include <iostream>

int main() {
 char name[50];
 
 std::cout << "Please enter your full name: ";
 std::cin.getline(name, 50); // ✅ Read entire line (including spaces)
 
 std::cout << "Hello," << name << "!" << std::endl;
 
 return 0;
}


5. Practice: Simple String Processing

▶ Example 1: Counting Vowels in a String (Difficulty ⭐⭐)

CPP
#include <iostream>
#include <cstring>

int main() {
 char str[100];
 std::cout << "Please enter a string: ";
 std::cin.getline(str, 100);
 
 int vowels = 0;
 for (int i = 0; i < std::strlen(str); i++) {
 char c = str[i];
 if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' ||
 c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U') {
 vowels++;
 }
 }
 
 std::cout << "Vowel count: " << vowels << std::endl;
 
 return 0;
}
▶ Try it Yourself

Output:

TEXT 📖 Display only
Please enter a string: 
Vowel count: 

Running result:

TEXT 📖 Display only
Please enter a string: Hello World
Vowel count: 3


6. Common Errors

(1) 6.1 Forgetting to Leave Space for \0

Error example:

TEXT 📖 Display only
#include <iostream>

int main() {
 char name[5] = "Hello"; // ❌ Error: "Hello" Need 6 chars (including \0), but array size is only 5
 std::cout << name << std::endl;
 return 0;
}

Fix:

CPP
char name[6] = "Hello"; // ✅ Correct:Array size must be at least 6

(2) 6.2 Using = to Assign a String

Error example:

TEXT 📖 Display only
#include <iostream>

int main() {
 char str1[20];
 char str2 = "Hello";
 
 str1 = str2; // ❌ Error: Cannot assign to array
 str1 = "World"; // ❌ Error: Cannot assign to array
 
 return 0;
}

Fix: Use strcpy

CPP
#include <iostream>
#include <cstring>

int main() {
 char str1[20];
 char str2 = "Hello";
 
 std::strcpy(str1, str2); // ✅ Correct:Use strcpy to copy
 std::cout << str1 << std::endl;
 
 return 0;
}

❓ FAQ

Q: When should I use C-style strings, and when should I use C++ strings? A: Prefer C++ strings (covered later), unless: > 1. You're maintaining legacy code (C code) > 2. You're doing very low-level optimization (C-style strings are more efficient)

C++ strings are safer and easier to use; recommended for beginners.

Q: Why does char name = "Hello" work, but int arr = {1, 2, 3} not work? A: Only string literals can directly initialize character arrays.

CPP
char name = "Hello"; // OK
int arr = {1, 2, 3}; // OK(this is an initializer list, not a string literal)

Q: How do I convert a C-style string to a C++ string?

A: You can assign directly (the C++ string constructor handles the conversion automatically).

CPP
#include `<iostream>`
#include `<string>`

int main() {
    char cstr[] = "Hello";
    std::string cppStr = cstr;  // Automatic conversion
    
    std::cout << cppStr << std::endl;
    return 0;
}

▶ Example 3: String Length and Copy (Difficulty ⭐)

CPP
#include <iostream>
#include <cstring>

int main() {
    char src[] = "Hello";
    char dest[20];

    std::cout << "src length: " << strlen(src) << std::endl;

    strcpy(dest, src);
    std::cout << "After copy: " << dest << std::endl;

    return 0;
}
▶ Try it Yourself

Output:

TEXT 📖 Display only
src length: 5
After copy: Hello
💡 Tip: C-style strings use strlen() to get the length and strcpy() to copy. Make sure the destination array is large enough!


📖 Summary


📝 Exercises

  1. Basic (Difficulty ⭐): Declare a C-style string char str = "Hello, World!", then output its length and each character.

  2. Intermediate (Difficulty ⭐⭐): Write a program that lets the user enter two strings and compares whether they are equal (using strcmp).

  3. Challenge (Difficulty ⭐⭐⭐): Write a program that implements "string reversal":

  4. Let the user enter a string

  5. Reverse it (e.g., "Hello" becomes "olleH")

  6. Implement it using C-style strings (no C++ string allowed)


11. 🚀 Next Step

Now that you've learned C-style strings, let's move on to C++ string (Lesson 19) — a safer, easier-to-use string class!

Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏