zoukankan      html  css  js  c++  java
  • Convertion between Number and String

    REFER:SO

    As of the C++11 standard, string-to-number conversion and vice-versa are built in into the standard library. All the following functions are present in <string> (as per paragraph 21.5).

    string to numeric

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

    Each of these take a string as input and will try to convert it to a number. If no valid number could be constructed, for example because there is no numeric data or the number is out-of-range for the type, an error is thrown.

    If conversion succeeded and *idx is not 0idx will contain the index of the first character that was not used for decoding. This could be an index behind the last character.

    Finally, the integral types allow to specify a base, for digits larger than 9, the alphabet is assumed (a=10until z=35). You can find more information about the exact formatting that can parsed here for floating-point numberssigned integers and unsigned integers.

    Finally, for each function there is also an overload that accepts a std::wstring as it's first parameter.

    numeric to string

    string to_string(int val);
    string to_string(unsigned val);
    string to_string(long val);
    string to_string(unsignedlong val);
    string to_string(longlong val);
    string to_string(unsignedlonglong val);
    string to_string(float val);
    string to_string(double val);
    string to_string(longdouble val);

    These are more straightforward, you pass the appropriate numeric type and you get a string back. For formatting options you should go back to the C++03 stringsream option and use stream manipulators, as explained in an other answer here.

    There are also similar functions defined that are named to_wstring, these will return a std::wstring.

  • 相关阅读:
    下定决心
    SPFA
    Linux下一些常用的命令
    如何设计符合RESTful风格的API
    django中的第三方:富文本编辑器和itsdangerous加密
    redis主从
    redis集群
    django中关联(一对多)查询的两种方式,理一理
    关于Django中的迁移文件
    日常工作中Git的正确使用姿势
  • 原文地址:https://www.cnblogs.com/invisible/p/3008715.html
Copyright © 2011-2022 走看看