How to convert a std::string to const char* or char*
If you just want to pass a std::string
to a function that needs const char*
you can use
std::string str;
const char * c = str.c_str();
If you want to get a writable copy, like char *
, you can do that with this:
std::string str;
char * writable = new char[str.size() + 1];
std::copy(str.begin(), str.end(), writable);
writable[str.size()] = '\0'; // don't forget the terminating 0
// don't forget to free the string after finished using it
delete[] writable;
Edit: Notice that the above is not exception safe. If anything between the new
call and the delete
call throws, you will leak memory, as nothing will call delete
for you automatically. There are two immediate ways to solve this.
boost::scoped_array
boost::scoped_array
will delete the memory for you upon going out of scope:
std::string str;
boost::scoped_array<char> writable(new char[str.size() + 1]);
std::copy(str.begin(), str.end(), writable.get());
writable[str.size()] = '\0'; // don't forget the terminating 0
// get the char* using writable.get()
// memory is automatically freed if the smart pointer goes
// out of scope
std::vector
This is the standard way (does not require any external library). You use std::vector
, which completely manages the memory for you.
std::string str;
std::vector<char> writable(str.begin(), str.end());
writable.push_back('\0');
// get the char* using &writable[0] or &*writable.begin()
How to convert string to const char[] in c++
With std::string
there is the function c_str()
(with the synonym data()
since C++11) to get a pointer to the underlying null-terminated character array:
std::string const myString{"stackoverflow"};
const char* cstr = myString.c_str();
const char* data = myString.data();
conversion between char* and std::string and const char*
std::string A = "hello"; //< assignment from char* to string
const char* const B = A.c_str(); //< call c_str() method to access the C string
std::string C = B; //< assignment works just fine (with allocation though!)
printf("%s", C.c_str()); //< pass to printf via %s & c_str() method
How to convert std::vectorstd::string to const char* array? [duplicate]
You can't convert it, but it's straightforward to create an array:
std::vector<const char*> strings;
for (int i = 0; i < list.size(); ++i)
strings.push_back(list[i].c_str();
And now, strings.data()
gives you an array of const char*
.
Note that strings
should not be used after list
has been destroyed, since it holds pointers to data that lives in list
. I'd probably wrap this in a function:
void call_C_function(const std::vector<std::string>& list) {
std::vector<const char*> strings;
for (int i = 0; i < list.size(); ++i)
strings.push_back(list[i].c_str());
c_function(strings.data());
}
That way, strings
will live only through the call to c_function
, and there is no danger of it outlasting list
.
How to convert std::string to const char*? [duplicate]
Use foobar.c_str()
.
You might find this link useful: http://www.cppreference.com/wiki/string/start
Convert std::string to const char* for printf Consumption
The problem with getMessage1 is that you return pointer to local variable which is deleted as soon as you leave this function giving you dangling pointer.
The simplest solution would be to make myString static if possible so its lifetime will be as long as the program itself.
const char* getMessage1() {
static std::string myString = "SomeOutput";
return myString.c_str();
}
int main() {
printf("#1: %s \n", getMessage1()); // prints #1: SomeOutput
return 0;
}
Link to working example on ideone
For some more examples see how to return pointer of local variable.
Difference between std::string and const char*?
std::string
will give you the ability to use its member functions and most importantly to modify its contents. The initial data will likely1 be copied to a dynamically allocated memory location when the program reaches its constructor. It will also store its size.
const char*
is only a pointer value that points to a constant that is gonna be baked into the binary. There's no size information stored, and all functions operating on it have to rely on the presence of the '\0'
value at the end.
1 It's possible that Small-String Optimization kicks in here.
Conversion of std:string to char*
When I run the code, an error appears when I call this function:
candidate function not viable: no known conversion from 'std::string' (aka 'basic_string') to 'char *' for 1st argument
You did not show the actual code that is trying to pass the std::string
to the receiver()
function, but the error message is very clear. You simply cannot assign a std::string
directly to a non-const char*
, which is exactly what the compiler is complaining about.
However, you can get a const char*
from a std::string
using its c_str()
method, and then you can const_cast
that to a char*
(as long as the function does not try to modify the char
data), eg:
std::string result = ...;
receiver(const_cast<char*>(result.c_str()), static_cast<int>(result.size()));
Or, you can simply use &result[0]
instead (which is guaranteed in C++11 and later to be contiguous and null-terminated), or you can use result.data()
in C++17 and later, eg:
std::string result = ...;
receiver(&result[0]/*result.data()*/, static_cast<int>(result.size()));
Or, you could simply change result
from std::string
to AnsiString
, as its c_str()
method returns a non-const char*
, eg:
AnsiString result = AnsiString::StringOfChar('0', 8) + myDataModule->getId();
receiver(result.c_str(), result.Length());
Either way, if receiver()
only needs to read from data
and not modify its content, then it should be changed to take data
as a const char*
instead (especially since that is what strcpy()
expects anyway), eg:
void receiver(const char * data, int num)
Then you can use result.c_str()
as-is, no trickery, whether result
is an AnsiString
or a std::string
.
C++ TCP Socket | cannot convert ‘std::__cxx11::string to ‘const char*’ | ‘server’ was not declared in this scope
For the first error, inet_pton()
expects a const char*
as input, but you are giving it a std::string
instead, which is not implicitly convertible to const char*
. You can simply call target.c_str()
to get one, though:
if(inet_pton(AF_INET, target.c_str(), &serv_addr.sin_addr)<=0)
For the second error, there is no server
variable defined. You need to change that to serv_addr
instead, and also const sockaddr*
needs to be changed to struct sockaddr*
(or the struct
omitted entirely, since this is C++):
connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr));
Or:
connect(sock, (sockaddr *)&serv_addr, sizeof(serv_addr));
Note that you are already making a similar call to connect()
just above your do..while
loop, and then calling it again inside your loop. You can't re-connect()
a TCP socket that is already connected. So you need to decide how many times you actually intend to call connect()
. Are you intending to make only 1 TCP connection? If so, then connect()
needs to be called before the loop. Or, do you intend to make multiple TCP connections, 1 per loop iteration? If so, note that you cannot reuse a socket after calling close()
on it, so you will need to call socket()
inside of the loop as well, to make a new socket for each connect()
.
Related Topics
Difference Between 'Typedef' and 'Using' in C++11
C++11 Rvalues and Move Semantics Confusion (Return Statement)
How to Expand a Tuple into Variadic Template Function'S Arguments
What Is the Easiest Way to Initialize a Std::Vector With Hardcoded Elements
Array Size At Run Time Without Dynamic Allocation Is Allowed
What Is a "Span" and When Should I Use One
How to Use Std::Maps With User-Defined Types as Key
What Exactly Is a Type Cast in C/C++
Why Should the Implementation and the Declaration of a Template Class Be in the Same Header File
Non-Const Reference Bound to Temporary, Visual Studio Bug
Why Does an Overridden Function in the Derived Class Hide Other Overloads of the Base Class
Is Local Static Variable Initialization Thread-Safe in C++11
Using Arrays or Std::Vectors in C++, What's the Performance Gap
How to Make My Custom Type to Work With "Range-Based For Loops"
Fast Bignum Square Computation
Implementation C++14 Make_Integer_Sequence
Avx2 What Is the Most Efficient Way to Pack Left Based on a Mask