Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a string to a char* in c++?

Tags:

I have an error in my program: "could not convert from string to char*". How do I perform this conversion?

like image 337
Ptichka Avatar asked Nov 11 '10 18:11

Ptichka


People also ask

Can I convert string to char *?

We can convert String to char in java using charAt() method of String class. The charAt() method returns a single character only. To get all characters, you can use loop.

Is char * A string in C?

This last part of the definition is important: all C-strings are char arrays, but not all char arrays are c-strings. C-strings of this form are called “string literals“: const char * str = "This is a string literal.

What char * means in C?

char* means a pointer to a character. In C strings are an array of characters terminated by the null character.

Is char * a string?

char* is a pointer to a character. char is a character. A string is not a character. A string is a sequence of characters.


1 Answers

If you can settle for a const char*, you just need to call the c_str() method on it:

const char *mycharp = mystring.c_str(); 

If you really need a modifiable char*, you will need to make a copy of the string's buffer. A vector is an ideal way of handling this for you:

std::vector<char> v(mystring.length() + 1); std::strcpy(&v[0], mystring.c_str()); char* pc = &v[0];
like image 136
Martin Broadhurst Avatar answered Oct 02 '22 15:10

Martin Broadhurst