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.

  • 相关阅读:
    Scrum会议5
    小组项目alpha发布的评价
    第二阶段冲刺记录三
    第二阶段冲刺记录二
    第13周学习进度
    第二阶段冲刺记录1
    《人月神话》阅读笔记01
    第12周学习进度
    意见汇总
    双人结对,四则运算(三阶段)
  • 原文地址:https://www.cnblogs.com/invisible/p/3008715.html
Copyright © 2011-2022 走看看