std:: string to char*


Quiero convertir un std::string en a char* o char[] tipo de datos.

std::string str = "string";
char* chr = str;

Resulta en: "error: no se puede convertir 'std::string' a 'char' ...".

¿Qué métodos hay disponibles para hacer esto?

Author: Mario, 2011-09-08

15 answers

No se convertirá automáticamente (gracias a dios). Tendrás que usar el método c_str() para obtener la versión de la cadena C.

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

Tenga en cuenta que devuelve un const char *; no se le permite cambiar la cadena de estilo C devuelta por c_str(). Si quieres procesarlo tendrás que copiarlo primero:

std::string str = "string";
char *cstr = new char[str.length() + 1];
strcpy(cstr, str.c_str());
// do stuff
delete [] cstr;

O en C++moderno:

std::vector<char> cstr(str.c_str(), str.c_str() + str.size() + 1);
 516
Author: orlp,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-20 18:35:41

Más detalles aquí, y aquí, pero se puede utilizar

string str = "some string" ;
char *cstr = &str[0u];
 113
Author: bobobobo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:02:47

Si necesitara una copia raw mutable del contenido de una cadena de c++, entonces haría esto:

std::string str = "string";
char* chr = strdup(str.c_str());

Y posteriores:

free(chr); 

Entonces, ¿por qué no juego con std::vector o new [] como cualquier otra persona? Porque cuando necesito una cadena de caracteres raw mutable de estilo C, entonces porque quiero llamar a código C que cambia la cadena y el código C desasigna cosas con free() y asigna con malloc() (strdup usa malloc). Así que si paso mi cadena raw a alguna función X escrita en C podría tener una restricción en su argumento que tiene que asignar en el montón (por ejemplo, si la función podría querer llamar a realloc en el parámetro). Pero es muy poco probable que se esperaría un argumento asignado con (algunos usuario redefinido) nuevo []!

 30
Author: Nordic Mainframe,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-09-08 20:28:56

(Esta respuesta solo se aplica a C++98.)

Por favor, no uses un raw char*.

std::string str = "string";
std::vector<char> chars(str.c_str(), str.c_str() + str.size() + 1u);
// use &chars[0] as a char*
 17
Author: ildjarn,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-20 10:07:32
  • Si solo desea una cadena de estilo C que represente el mismo contenido:

    char const* ca = str.c_str();
    
  • Si desea una cadena de estilo C con nuevo contenido , una forma (dado que no conoce el tamaño de la cadena en tiempo de compilación) es la asignación dinámica:

    char* ca = new char[str.size()+1];
    std::copy(str.begin(), str.end(), ca);
    ca[str.size()] = '\0';
    

    No te olvides de delete[] después.

  • Si desea una matriz de longitud limitada y asignada estáticamente en su lugar:

    size_t const MAX = 80; // maximum number of chars
    char ca[MAX] = {};
    std::copy(str.begin(), (str.size() >= MAX ? str.begin() + MAX : str.end()), ca);
    

std::string no convierte implícitamente a estos tipos para el la razón simple que necesita hacer esto es generalmente un olor del diseño. Asegúrate de que realmente lo necesitas.

Si definitivamente necesita un char*, el mejor a es probablemente:

vector<char> v(str.begin(), str.end());
char* ca = &v[0]; // pointer to start of vector
 11
Author: Lightness Races in Orbit,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-07-10 09:56:47

Esto sería mejor como un comentario sobre la respuesta de bobobobo, pero no tengo el rep para eso. Logra lo mismo pero con mejores prácticas.

Aunque las otras respuestas son útiles, si alguna vez necesitas convertir std::string a char* explícitamente sin const, const_cast es tu amigo.

std::string str = "string";
char* chr = const_cast<char*>(str.c_str());

Tenga en cuenta que esto no le dará una copia de los datos; le dará un puntero a la cadena. Por lo tanto, si modifica un elemento de chr, modificará str.

 6
Author: hairlessbear,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-18 00:46:56

Suponiendo que solo necesita una cadena de estilo C para pasar como entrada:

std::string str = "string";
const char* chr = str.c_str();
 4
Author: Mark B,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-09-08 17:27:25

Para ser estrictamente pedante, no puede "convertir una cadena std::en un tipo de datos char* o char []."

Como han mostrado las otras respuestas, puede copiar el contenido de la cadena std::a una matriz char, o hacer un const char* al contenido de la cadena std::para que pueda acceder a ella en un "estilo C".

Si está tratando de cambiar el contenido de la cadena std::, el tipo std::string tiene todos los métodos para hacer cualquier cosa que pueda necesitar.

Si eres tratando de pasarlo a alguna función que toma un char*, está std:: string:: c_str().

 4
Author: Rob K,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-09-08 18:03:03

Para completar' sake, no se olvide std::string::copy().

std::string str = "string";
const size_t MAX = 80;
char chrs[MAX];

str.copy(chrs, MAX);

std::string::copy() no termina. Si necesita asegurar un terminador NUL para su uso en funciones de cadena de C:

std::string str = "string";
const size_t MAX = 80;
char chrs[MAX];

memset(chrs, '\0', MAX);
str.copy(chrs, MAX-1);
 3
Author: Jeffery Thomas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-05-12 00:43:23

Aquí hay una versión más robusta de Protocol Buffer

char* string_as_array(string* str)
{
    return str->empty() ? NULL : &*str->begin();
}

// test codes
std::string mystr("you are here");
char* pstr = string_as_array(&mystr);
cout << pstr << endl; // you are here
 3
Author: zangw,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-16 09:18:30
char* result = strcpy((char*)malloc(str.length()+1), str.c_str());
 2
Author: cegprakash,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-07-17 12:48:26

Alternativamente, puede usar vectores para obtener un carácter escribible * como se muestra a continuación;

//this handles memory manipulations and is more convenient
string str;
vector <char> writable (str.begin (), str.end) ;
writable .push_back ('\0'); 
char* cstring = &writable[0] //or &*writable.begin () 

//Goodluck  
 2
Author: ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-09 00:46:12

Puedes hacerlo usando el iterador.

std::string str = "string";
std::string::iterator p=str.begin();
char* chr = &(*p);

Buena suerte.

 2
Author: TS.PARK,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-09 10:24:02

Esto también funcionará

std::string s;
std::cout<<"Enter the String";
std::getline(std::cin, s);
char *a=new char[s.size()+1];
a[s.size()]=0;
memcpy(a,s.c_str(),s.size());
std::cout<<a;  
 1
Author: Genocide_Hoax,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-05-28 07:59:44

Una versión segura de la respuesta char* de orlp usando unique_ptr:

std::string str = "string";
auto cstr = std::make_unique<char[]>(str.length() + 1);
strcpy(cstr.get(), str.c_str());
 1
Author: Enhex,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-25 09:11:24