zoukankan      html  css  js  c++  java
  • C++中int与string的相互转换

    一、int转string

    1.c++11标准增加了全局函数std::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);

    Example:

    // to_string example
    #include <iostream> // std::cout
    #include <string> // std::string, std::to_string

    int main ()
    {
    std::string pi = "pi is " + std::to_string(3.1415926);
    std::string perfect = std::to_string(1+2+4+7+14) + " is a perfect number";
    std::cout << pi << ' ';
    std::cout << perfect << ' ';
    return 0;
    }
    Output:
    pi is 3.141593
    28 is a perfect number
    2.采用sstream中定义的字符串流对象来实现
    ostringstream os; //构造一个输出字符串流,流内容为空
    int i = 12;
    os << i; //向输出字符串流中输出int整数i的内容
    cout << os.str() << endl; //利用字符串流的str函数获取流中的内容

    二、string转int
    1.可以使用std::stoi/stol/stoll等等函数
    Example:

    // stoi example
    #include <iostream> // std::cout
    #include <string> // std::string, std::stoi

    int main ()
    {
    std::string str_dec = "2001, A Space Odyssey";
    std::string str_hex = "40c3";
    std::string str_bin = "-10010110001";
    std::string str_auto = "0x7f";

    std::string::size_type sz; // alias of size_t

    int i_dec = std::stoi (str_dec,&sz);
    int i_hex = std::stoi (str_hex,nullptr,16);
    int i_bin = std::stoi (str_bin,nullptr,2);
    int i_auto = std::stoi (str_auto,nullptr,0);

    std::cout << str_dec << ": " << i_dec << " and [" << str_dec.substr(sz) << "] ";
    std::cout << str_hex << ": " << i_hex << ' ';
    std::cout << str_bin << ": " << i_bin << ' ';
    std::cout << str_auto << ": " << i_auto << ' ';

    return 0;
    }
    Output:
    2001, A Space Odyssey: 2001 and [, A Space Odyssey]
    40c3: 16579
    -10010110001: -1201
    0x7f: 127
    2.采用标准库中atoi函数,对于其他类型也都有相应的标准库函数,比如浮点型atof(),long型atol()等等
    string s = "12";
    int a = atoi(s.c_str());
    3.采用sstream头文件中定义的字符串流对象来实现转换
    istringstream is("12"); //构造输入字符串流,流的内容初始化为“12”的字符串
    int i;
    is >> i; //从is流中读入一个int整数存入i中

    参考资料:
    http://blog.csdn.net/chavo0/article/details/51038397

    http://blog.csdn.net/na_beginning/article/details/53576123


    ————————————————
    版权声明:本文为CSDN博主「HarryLi」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
    原文链接:https://blog.csdn.net/u010510020/article/details/73799996

  • 相关阅读:
    元类
    redis--py链接redis【转】
    redis--py操作redis【转】
    python format 用法详解
    初识多线程__下
    mysql学习笔记五 —— MHA
    mysql学习笔记四 —— AB复制
    mysql学习笔记三 —— 数据恢复与备份
    mysql学习笔记二 —— 权限体系
    mysql学习笔记一 —— 数据的增删改查
  • 原文地址:https://www.cnblogs.com/renzmin/p/11803495.html
Copyright © 2011-2022 走看看