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:

 

 
  1. // to_string example

  2. #include <iostream> // std::cout

  3. #include <string> // std::string, std::to_string

  4.  
  5. int main ()

  6. {

  7. std::string pi = "pi is " + std::to_string(3.1415926);

  8. std::string perfect = std::to_string(1+2+4+7+14) + " is a perfect number";

  9. std::cout << pi << '\n';

  10. std::cout << perfect << '\n';

  11. return 0;

  12. }

Output:

 

 
  1. pi is 3.141593

  2. 28 is a perfect number

2.采用sstream中定义的字符串流对象来实现

 

 
  1. ostringstream os; //构造一个输出字符串流,流内容为空

  2. int i = 12;

  3. os << i; //向输出字符串流中输出int整数i的内容

  4. cout << os.str() << endl; //利用字符串流的str函数获取流中的内容


二、string转int

1.可以使用std::stoi/stol/stoll等等函数
Example:

 

 
  1. // stoi example

  2. #include <iostream> // std::cout

  3. #include <string> // std::string, std::stoi

  4.  
  5. int main ()

  6. {

  7. std::string str_dec = "2001, A Space Odyssey";

  8. std::string str_hex = "40c3";

  9. std::string str_bin = "-10010110001";

  10. std::string str_auto = "0x7f";

  11.  
  12. std::string::size_type sz; // alias of size_t

  13.  
  14. int i_dec = std::stoi (str_dec,&sz);

  15. int i_hex = std::stoi (str_hex,nullptr,16);

  16. int i_bin = std::stoi (str_bin,nullptr,2);

  17. int i_auto = std::stoi (str_auto,nullptr,0);

  18.  
  19. std::cout << str_dec << ": " << i_dec << " and [" << str_dec.substr(sz) << "]\n";

  20. std::cout << str_hex << ": " << i_hex << '\n';

  21. std::cout << str_bin << ": " << i_bin << '\n';

  22. std::cout << str_auto << ": " << i_auto << '\n';

  23.  
  24. return 0;

  25. }

Output:

 
  1. 2001, A Space Odyssey: 2001 and [, A Space Odyssey]

  2. 40c3: 16579

  3. -10010110001: -1201

  4. 0x7f: 127

2.采用标准库中atoi函数,对于其他类型也都有相应的标准库函数,比如浮点型atof(),long型atol()等等

 
  1. string s = "12";

  2. int a = atoi(s.c_str());

3.采用sstream头文件中定义的字符串流对象来实现转换

 

 
  1. istringstream is("12"); //构造输入字符串流,流的内容初始化为“12”的字符串

  2. int i;

  3. is >> i; //从is流中读入一个int整数存入i中


参考资料:

http://blog.csdn.net/chavo0/article/details/51038397

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

转载来源:https://blog.csdn.net/u010510020/article/details/73799996

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值