How to Convert a Const Char * to Std::String

Converting a const char * to std::string

std::stringhas a constructor fromconst char *.This means that it is legal to write:

const char* str="hello";
std::string s = str;

How to convert a const char * to std::string

This page on string::string gives two potential constructors that would do what you want:

string ( const char * s, size_t n );
string ( const string& str, size_t pos, size_t n = npos );

Example:

#include<cstdlib>
#include<cstring>
#include<string>
#include<iostream>
using namespace std;

int main(){

char* p= (char*)calloc(30, sizeof(char));
strcpy(p, "Hello world");

string s(p, 15);
cout << s.size() << ":[" << s << "]" << endl;
string t(p, 0, 15);
cout << t.size() << ":[" << t << "]" << endl;

free(p);
return 0;
}

Output:

15:[Hello world]
11:[Hello world]

The first form considers p to be a simple array, and so will create (in our case) a string of length 15, which however prints as a 11-character null-terminated string with cout << .... Probably not what you're looking for.

The second form will implicitly convert the char* to a string, and then keep the maximum between its length and the n you specify. I think this is the simplest solution, in terms of what you have to write.

convert a char* to std::string

std::string has a constructor for this:

const char *s = "Hello, World!";
std::string str(s);

Note that this construct deep copies the character list at s and s should not be nullptr, or else behavior is undefined.

Can we assign const char* to a string in cpp?

You absolutely can.

std::string was meant to replace the tedious and error-prone C strings const char* so for it to be a good replacement/successor it'd need backwards compatibility with const char* which it does.

name = name2; calls operator= so if we check basic_strings overloads for this operator we can see (3):

basic_string& operator=( const CharT* s );

Here CharT is of the type char so you get const char*

Which does what you'd expect it to do, it copies over the contents the const char* is pointing to, to the internal buffer of std::string:

Replaces the contents with those of null-terminated character string
pointed to by s as if by assign(s, Traits::length(s)).

In order to go the other route though, from a std::string to a const char*, you'd need to call its method c_str() on the std::string object.

How to convert char* to std::string

std::string has a constructor for this:

const char *str = "Shravan Kumar";
std::string str(str);

Just make sure that your char * isn't NULL, otherwise it will lead to undefined behavior.

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 .c_str():

std::string str;
const char * c = str.c_str();

And if you need a non-const char *, call .data():

std::string str;
char * c = str.data();

.data() was added in C++17. Before that, you can use &str[0].

Note that if the std::string is const, .data() will return const char * instead, like .c_str().

The pointer becomes invalid if the string is destroyed or reallocates memory.

The pointer points to a null-terminated string, and the terminator doesn't count against str.size(). You're not allowed to assign a non-null character to the terminator.

How to store a const char* in std :: string?

You can just re-assign:

const char *buf1 = "abc";
const char *buf2 = "def";

std::string str(buf1);

str = buf2; // Calls str.operator=(const char *)

How to convert std::vectorstd::string to const char* array?

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.

Converting string to const* char

It seems that function Notice have the first parameter of type const char * However the expression passed to it as the first argument

killerName + "has slain:" + victimName

has type std::string

Simply call the function the following way

Notice( ( killerName + "has slain:" + victimName ).c_str(), killer.GetMapIndex(), false); 

const char* concatenation

In your example one and two are char pointers, pointing to char constants. You cannot change the char constants pointed to by these pointers. So anything like:

strcat(one,two); // append string two to string one.

will not work. Instead you should have a separate variable(char array) to hold the result. Something like this:

char result[100];   // array to hold the result.

strcpy(result,one); // copy string one into the result.
strcat(result,two); // append string two to the result.


Related Topics



Leave a reply



Submit