• C++ 字符串与数字之间的转换


    1. 数字转字符串

    方法一

    使用C++11标准新增的to_string函数:

    string to_string (int val);
    string to_string (long val);
    string to_string (long long val);
    string to_string (unsigned val);
    string to_string (unsigned 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);
    

    测试:

    int i = 100123;
    double d = 100.123;
    cout << to_string(i) << endl;
    cout << to_string(d) << endl;
    

    输出:

    10123
    100.123000
    

    方法二

    使用stringstream类:

    template<typename out_type, typename in_value>
    out_type convert(const in_value & t){
        stringstream stream;
        stream << t;//向流中传值
        out_type result;//这里存储转换结果
        stream >> result;//向result中写入值
        return result;
    }
    

    测试:

    int i = 100123;
    double d = 100.123;
    cout << itos(i) << endl;
    cout << dtos(d) << endl;
    

    输出:

    100123
    100.123
    

    2. 字符串转数字

    字符串类提供了一系列的转换函数:

    stoi    // Convert string to integer (function template )
    stol    // Convert string to long int (function template )
    stoul   // Convert string to unsigned integer (function template )
    stoll   // Convert string to long long (function template )
    stoull  // Convert string to unsigned long long (function template )
    stof    // Convert string to float (function template )
    stod    // Convert string to double (function template )
    stold   // Convert string to long double (function template )
    

    测试:

    cout << stoi("123123") << endl;
    cout << stod("123.123") << endl;
    

    输出:

    123123
    123.123
    
    CS专业在读,热爱编程。
    专业之外,喜欢阅读,尤爱哲学、金庸、马尔克斯。
  • 相关阅读:
    2020牛客暑期多校(三)
    贪心算法
    高级搜索题集
    状态压缩dp
    [kuangbin带你飞]专题二 搜索进阶
    [kuangbin带你飞]专题一 简单搜索
    HDU 1695 GCD(求两区间的互质数对+容斥原理)
    UVA 10200 Prime Time(简单素数判定预处理)
    HDU 1452 FZU 1053 Happy 2004(逆元函数+因子和函数+大指数取模化简公式)
    低三位的数是8的倍数就可以被8整除
  • 原文地址:https://www.cnblogs.com/jmhwsrr/p/14587105.html
Copyright © 2020-2023  润新知