Convertir una cadena de estilo C a una C++ std::string


¿Cuál es la mejor manera de convertir una cadena de estilo C a un C++ std::string? En el pasado lo he hecho usando stringstream s. ¿Hay una mejor manera?

Author: templatetypedef, 2011-01-22

6 answers

Las cadenas de C++ tienen un constructor que le permite convertir cadenas de estilo C:

char* myStr = "This is a C string!";
std::string myCppString = myStr;
 43
Author: templatetypedef,
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-01-21 23:25:04

Compruebe los diferentes constructores de la clase string: documentación Quizás te interese:

//string(char* s)
std::string str(cstring);

Y:

//string(char* s, size_t n)
std::string str(cstring, len_str);
 6
Author: Santiago Alessandri,
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-08-28 17:26:05

Si quieres decir char* a std::string, puedes usar el constructor.

char* a;
std::string s(a);

O si el string s ya existe, simplemente escriba esto:

s=std::string(a);
 4
Author: Manas,
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-11 01:40:44

Puedes inicializar un std::string directamente desde una c-string:

std::string s = "i am a c string";
std::string t = std::string("i am one too");
 3
Author: trojanfoe,
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-01-21 23:25:30

C++11: Sobrecarga un operador literal de cadena

std::string operator ""_s(const char * str, std::size_t len) {
    return std::string(str, len);
}

auto s1 = "abc\0\0def";     // C style string
auto s2 = "abc\0\0def"_s;   // C++ style std::string

C++14: Usar el operador de std::string_literals espacio de nombres

using namespace std::string_literals;

auto s3 = "abc\0\0def"s;    // is a std::string
 3
Author: Shreevardhan,
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-07-08 12:24:58

En general (sin declarar nuevo almacenamiento) puede usar el constructor 1-arg para cambiar la cadena c a una cadena rvalue:

string xyz = std::string("this is a test") + 
             std::string(" for the next 60 seconds ") + 
             std::string("of the emergency broadcast system.");

Sin embargo, esto no funciona cuando se construye la cadena para pasarla por referencia a una función (un problema que acabo de encontrar), por ejemplo,

void ProcessString(std::string& username);
ProcessString(std::string("this is a test"));   // fails

Necesita hacer de la referencia una referencia const:

void ProcessString(const std::string& username);
ProcessString(std::string("this is a test"));   // works.
 1
Author: user216843,
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-05-09 20:51:56