web-dev-qa-db-fra.com

std :: lexical_cast - existe-t-il une telle chose?

La bibliothèque standard C++ définit-elle cette fonction ou dois-je recourir à Boost?

J'ai cherché sur le Web et je n'ai rien trouvé à part Boost, mais j'ai pensé que je ferais mieux de demander ici.

72
smallB

Seulement partiellement.

C++ 11 <string> A std::to_string Pour les types intégrés:

[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);

Renvoie: Chaque fonction renvoie un objet string contenant la représentation en caractères de la valeur de son argument qui serait générée en appelant la fonction sprintf(buf, fmt, val) avec un spécificateur de format de "%d", "%u", "%ld", "%lu", "%lld", "%llu" , "%f", "%f" Ou "%Lf", Respectivement, où buf désigne un tampon de caractères interne de taille suffisante.

Il y a aussi les éléments suivants qui vont dans l'autre sens:

[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);

Cependant, il n'y a rien de générique que vous pouvez utiliser (au moins pas avant TR2 , peut-être!), Et rien du tout en C++ 03.

Non, ce n'est pas le cas, même en C++ 11, mais c'est proposé pour inclusion dans le rapport technique 2, le prochain ensemble d'extensions de bibliothèque std.

18
CharlesB

Il n'y a pas de std :: lexical_cast, mais vous pouvez toujours faire quelque chose de similaire avec 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;
}
12
luke

Non, c'est une pure chose Boost seulement.

5

Si vous ne voulez pas booster, une bibliothèque légère appelée fmt implémente ce qui suit:

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

Plus d'exemples de la page officielle .

Accès aux arguments par position:

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"

Aligner le texte et spécifier une largeur:

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***********"

Remplacer% + f,% -f et% f et spécifier un signe:

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"

Remplacement de% x et% o et conversion de la valeur en différentes 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
Sandu Liviu Catalin