what throwing strtoint stoi parse not library invalid_argument ejemplos declared called after c++ parsing casting std c++-standard-library

c++ - throwing - std:: lexical_cast-¿existe tal cosa?



strtoint c++ (5)

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; }

¿La biblioteca estándar de C ++ define esta función o debo recurrir a Boost?

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


No, es solo algo puro de Boost.


No, no lo es, incluso en C ++ 11, pero se propone su inclusión en el Informe técnico 2, el siguiente conjunto de extensiones de la biblioteca std.


Si no quiere impulsar, entonces una biblioteca liviana 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 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"

Alineación del texto y especificación de 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"


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 de string que contiene la representación de caracteres del valor de su argumento que se generaría al llamar a sprintf(buf, fmt, val) con un especificador de formato de "%d" , "%u" , "%ld" , "%lu" , "%lld" , "%llu" , "%f" , "%f" o "%Lf" , respectivamente, donde buf designa un búfer de caracteres interno de tamaño suficiente.

También hay los siguientes que van al revés:

[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 puedas usar (¡al menos no hasta TR2 , tal vez!), Y nada en C ++ 03.