/*
* Converting a std::string to a character array in C++.
*
* In modern C++, a std::string already stores a sequence of characters.
* However, some APIs or algorithms may require the characters in a
* separate container such as std::vector<char>.
*
* This example demonstrates:
* - A dedicated conversion function
* - Const-correctness
* - Safe memory management via standard library containers
* - Clear documentation and error-free resource handling
*/
#include <iostream>
#include <string>
#include <vector>
/*
* Converts a std::string into a std::vector<char>.
*
* Parameters:
* text - The source string.
*
* Returns:
* A vector containing each character from the string.
*
* Implementation note:
* The vector constructor accepts a range defined by iterators.
* This efficiently copies all characters from the string into
* the resulting vector.
*/
std::vector<char> stringToCharArray(const std::string& text)
{
return std::vector<char>(text.begin(), text.end());
}
int main()
{
const std::string text = "Hello, World!";
// Convert the string to a character array representation.
const std::vector<char> characters = stringToCharArray(text);
std::cout << "Original string: " << text << '\n';
std::cout << "\nCharacter array contents:\n";
for (std::size_t i = 0; i < characters.size(); ++i) {
std::cout << "characters[" << i << "] = '"
<< characters[i] << "'\n";
}
}
/*
run:
Original string: Hello, World!
Character array contents:
characters[0] = 'H'
characters[1] = 'e'
characters[2] = 'l'
characters[3] = 'l'
characters[4] = 'o'
characters[5] = ','
characters[6] = ' '
characters[7] = 'W'
characters[8] = 'o'
characters[9] = 'r'
characters[10] = 'l'
characters[11] = 'd'
characters[12] = '!'
*/