Convert char array to a string in C++
This post will discuss how to convert a char array to a C++ string.
1. Using String Constructor
One way to convert a char array to a string in C++ is to use the string constructor. The string class has several constructors that can create a string object from different types of arguments, such as another string, a character, or an iterator range. One of these constructors can create a string object from a char array or a pointer to an array of characters (such as a C-string).
|
1 2 3 4 5 6 7 8 9 10 11 12 |
#include <iostream> int main() { char arr[] = "Techie Delight"; std::string s(arr); std::cout << s; // Techie Delight return 0; } |
2. Using operator=
Another alternative is to directly assign a char[] to a std::string. This works as operator= is overloaded for std::string, and a C-string would be copied to the string.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
#include <iostream> int main() { char arr[] = "Techie Delight"; std::string s = arr; std::cout << s; // Techie Delight return 0; } |
That’s all about converting a char array to a string in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)