In this article, we will be focusing on the different ways to convert String to char array and char array to String in C++. While dealing with String data, we may need to convert the string data items to character array and vice-versa. This tutorial will help you solve exactly that.
C++ provides us with the following techniques to convert a string to char array:
C++ c_str()
function along with C++ String strcpy()
function can be used to convert a string to char array easily.
The c_str() method represents the sequence of characters in an array of string followed by a null character (‘\0’). It returns a null pointer to the string.
Syntax:
Example:
Output:
For the conversion of char array to a string, we can use C++ for loops with ease.
Example:
Output:
The mentioned techniques can be used to convert a char array to string in C++:
C++ provides us with '+' operator
to concatenate or add data items to a variable.
Example:
Output:
C++ has got the concept of overloading which makes an operator perform other operations apart from the basic or default operation.
'=' operator
to store the data items character by character into the newly created empty string.Example:
Output:
In the context of conversion of char array to string, we can use C++ String Constructor for the same.
Syntax:
This constructor takes a sequence of characters terminated by a null character as an input parameter.
Note: This constructor string string()
can be used only at the time of string declaration throughout the program.
Example:
Output:
In this article, we have understood various techniques to convert string to char array and vice-versa in C++.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
Example (1) doesnt compile with visual studio 2019. Error type: error C2131: expression did not evaluate to a constant 1>C:\Users\tmcla\source\repos\ConsoleApplication35\ConsoleApplication35.cpp(12,24): message : failure was caused by call of undefined function or one not declared ‘constexpr’ 1>C:\Users\tmcla\source\repos\ConsoleApplication35\ConsoleApplication35.cpp(12,24): message : see usage of ‘std::basic_string<char,std::char_traits,std::allocator>::length’ must have a constant value. How can I rewrite this to a successful compile? Would a vector construction work better?
- Terrence McLaughlin