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.

  • 相关阅读:
    浅谈管道模型(Pipeline)
    经常使用的webservice接口
    2012年终总结
    【Linux】linux经常使用基本命令
    php:兄弟连之面向对象版图形计算器1
    学习selenium所须要具备的技术
    Sftp和ftp 差别、工作原理等(汇总ing)
    对数据分布进行可视化的方法
    FusionCharts简单教程(一)---建立第一个FusionCharts图形
    闭包和柯里化
  • 原文地址:https://www.cnblogs.com/invisible/p/3008715.html
Copyright © 2011-2022 走看看