std:: lexical cast - ¿existe tal cosa?


¿La Biblioteca Estándar de C++ define esta función, o tengo que recurrir a Boost?

Busqué en la web y no pude encontrar nada excepto Boost, pero pensé que sería mejor preguntar aquí.

Author: einpoklum, 2011-11-09

5 answers

Solo parcialmente.

C++11 <string> tiene std::to_string para los tipos incorporados:

[n3290: 21.5/7]:

string to_string(int val);
string to_string(unsigned val);
string to_string(long val);
string to_string(unsigned long val);
string to_string(long long val);
string to_string(unsigned long long val);
string to_string(float val);
string to_string(double val);
string to_string(long double val);

Devuelve: Cada función devuelve un objeto string que contiene representación de carácter del valor de su argumento que sería se genera llamando a sprintf(buf, fmt, val) con un formato el especificador de "%d", "%u", "%ld", "%lu", "%lld", "%llu", "%f", "%f", o "%Lf", respectivamente, donde buf designa un búfer de caracteres interno de suficiente Tamaño.

También hay los siguientes que van al revés: {[19]]}

[n3290: 21.5/1, 21.5/4]:

int stoi(const string& str, size_t *idx = 0, int base = 10);
long stol(const string& str, size_t *idx = 0, int base = 10);
unsigned long stoul(const string& str, size_t *idx = 0, int base = 10);
long long stoll(const string& str, size_t *idx = 0, int base = 10);
unsigned long long stoull(const string& str, size_t *idx = 0, int base = 10);
float stof(const string& str, size_t *idx = 0);
double stod(const string& str, size_t *idx = 0);
long double stold(const string& str, size_t *idx = 0);

Sin embargo, no hay nada genérico que pueda usar (al menos no hasta TR2, tal vez!), y nada en absoluto en C++03.

 83
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
2011-11-09 14:12:16

No, no lo es, incluso en C++11, pero es propuesto para su inclusión en el Informe Técnico 2, el siguiente conjunto de extensiones de biblioteca std.

 18
Author: CharlesB,
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-11-09 13:05:20

No hay std:: lexical_cast, pero siempre puedes hacer algo similar con stringstreams :

template <typename T>
T lexical_cast(const std::string& str)
{
    T var;
    std::istringstream iss;
    iss.str(str);
    iss >> var;
    // deal with any error bits that may have been set on the stream
    return var;
}
 11
Author: luke,
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-11-09 13:14:08

No, es solo un impulso puro.

 5
Author: Some programmer dude,
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-11-09 13:05:30

Si no desea boost, entonces una biblioteca ligera llamada fmt implementa lo siguiente:

// Works with all the C++11 features and AFAIK faster then boost or standard c++11
std::string string_num = fmt::FormatInt(123456789).str(); // or .c_str()

Más ejemplos de la página oficial .

Accediendo a los argumentos por posición:

format("{0}, {1}, {2}", 'a', 'b', 'c');
// Result: "a, b, c"
format("{}, {}, {}", 'a', 'b', 'c');
// Result: "a, b, c"
format("{2}, {1}, {0}", 'a', 'b', 'c');
// Result: "c, b, a"
format("{0}{1}{0}", "abra", "cad");  // arguments' indices can be repeated
// Result: "abracadabra"

Alineando el texto y especificando un ancho:

format("{:<30}", "left aligned");
// Result: "left aligned                  "
format("{:>30}", "right aligned");
// Result: "                 right aligned"
format("{:^30}", "centered");
// Result: "           centered           "
format("{:*^30}", "centered");  // use '*' as a fill char
// Result: "***********centered***********"

Reemplazando % + f, % - f y % f y especificando un signo:

format("{:+f}; {:+f}", 3.14, -3.14);  // show it always
// Result: "+3.140000; -3.140000"
format("{: f}; {: f}", 3.14, -3.14);  // show a space for positive numbers
// Result: " 3.140000; -3.140000"
format("{:-f}; {:-f}", 3.14, -3.14);  // show only the minus -- same as '{:f}; {:f}'
// Result: "3.140000; -3.140000"

Reemplazando %x y %o y convirtiendo el valor a diferentes bases:

format("int: {0:d};  hex: {0:x};  oct: {0:o}; bin: {0:b}", 42);
// Result: "int: 42;  hex: 2a;  oct: 52; bin: 101010"
// with 0x or 0 or 0b as prefix:
format("int: {0:d};  hex: {0:#x};  oct: {0:#o};  bin: {0:#b}", 42);
// Result: "int: 42;  hex: 0x2a;  oct: 052;  bin: 0b101010"
 4
Author: Sandu Liviu Catalin,
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-05-08 16:59:37