Convert a C-string to std::string in C++
In this quick article, we’ll explore how to convert a C-string to std::string in C++.
1. Using string constructor
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
#include <iostream> int main() { // C-style string const char* cstr = "Techie Delight"; // string constructor accepts `const char*` as a parameter std::string s(cstr); std::cout << s << std::endl; return 0; } |
2. Using std::string::append function
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
#include <iostream> int main() { // C-style string const char* cstr = "Techie Delight"; std::string s; s.append(cstr); std::cout << s << std::endl; return 0; } |
3. Using std::string::assign function
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
#include <iostream> int main() { // C-style string const char* cstr = "Techie Delight"; std::string s; s.assign(cstr); std::cout << s << std::endl; return 0; } |
4. Using + operator
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
#include <iostream> int main() { // C-style string const char* cstr = "Techie Delight"; std::string s; s += cstr; std::cout << s << std::endl; return 0; } |
It is worth noting that all the above solutions will error out if char* is NULL.
That’s all about converting a C-string to std::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 :)