const char to string
To convert a const char*
to a std::string
in C++, you can follow these steps:
Include the necessary header files: Make sure to include the
<string>
header file, which provides thestd::string
class.Declare a
const char
variable: Start by declaring aconst char
variable that holds the character array you want to convert to a string. For example,const char* cstr = "Hello, World!";
.Create a
std::string
object: Use thestd::string
constructor to create a string object from theconst char
. Pass theconst char
variable as the argument to the constructor. For example,std::string str(cstr);
.Use the converted string: You can now use the
std::string
object (str
) as you would with any other string. For example, you can print it to the console, concatenate it with other strings, or perform any other string operations.
Here's an example that puts all these steps together:
#include <iostream>
#include <string>
int main() {
const char* cstr = "Hello, World!";
std::string str(cstr);
std::cout << "Converted string: " << str << std::endl;
return 0;
}
In this example, the const char*
variable cstr
is converted to a std::string
object str
. Then, the converted string is printed to the console using std::cout
.