Converting a std::string
to a char*
is a common operation in C++ programming, especially when dealing with functions or APIs that require C-style strings. While std::string
provides powerful string manipulation capabilities, sometimes you may need to convert it to a C-style string for compatibility reasons. This tutorial explains how to convert std::string
to C-style string.
const char*
Use c_str
function to convert std::string
to const char*
. The returned pointer points to a constant array of characters, and you are not allowed to modify the content of the string through this pointer.
#include <iostream>
int main()
{
std::string str = "Hello world";
const char *cstr = str.c_str();
std::cout << cstr << std::endl;
return 0;
}
char*
Use data
function to convert std::string
to char*
. It provides a non-constant pointer, allowing you to modify the content of the string through this pointer.
#include <iostream>
int main()
{
std::string str = "Hello world";
char *cstr = str.data();
std::cout << cstr << std::endl;
return 0;
}
Both c_str
and data
functions ensure that the returned pointer points to a null-terminated sequence of characters, making it suitable for use with functions expecting C-style strings.
Leave a Comment
Cancel reply