zoukankan      html  css  js  c++  java
  • 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专业在读,热爱编程。
    专业之外,喜欢阅读,尤爱哲学、金庸、马尔克斯。
  • 相关阅读:
    mysql的复制
    web页面请求历程
    django工作原理简介
    http协议
    路由器和交换机的区别
    OSI七层模型
    TCP/IP协议总结
    IO复用
    僵尸进程和孤儿进程
    java源代码如何打成jar包
  • 原文地址:https://www.cnblogs.com/jmhwsrr/p/14587105.html
Copyright © 2011-2022 走看看