C++string与int的相互转换(使用C++11)

一、int转string


 
 
  1. #include <iostream>
  2. #include <string>
  3. int main()
  4. {
  5. double f = 23.43;
  6. double f2 = 1e-9;
  7. double f3 = 1e40;
  8. double f4 = 1e-40;
  9. double f5 = 123456789;
  10. std:: string f_str = std::to_string(f);
  11. std:: string f_str2 = std::to_string(f2); // 注意:返回 "0.000000"
  12. std:: string f_str3 = std::to_string(f3); // 注意:不返回 "1e+40".
  13. std:: string f_str4 = std::to_string(f4); // 注意:返回 "0.000000"
  14. std:: string f_str5 = std::to_string(f5);
  15. std:: cout << "std::cout: " << f << '\n'
  16. << "to_string: " << f_str << "\n\n"
  17. << "std::cout: " << f2 << '\n'
  18. << "to_string: " << f_str2 << "\n\n"
  19. << "std::cout: " << f3 << '\n'
  20. << "to_string: " << f_str3 << "\n\n"
  21. << "std::cout: " << f4 << '\n'
  22. << "to_string: " << f_str4 << "\n\n"
  23. << "std::cout: " << f5 << '\n'
  24. << "to_string: " << f_str5 << '\n';
  25. }

输出


  
  
  1. std:: cout: 23.43
  2. to_string: 23.430000
  3.  
  4. std:: cout: 1e-09
  5. to_string: 0.000000
  6.  
  7. std:: cout: 1e+40
  8. to_string: 10000000000000000303786028427003666890752.000000
  9.  
  10. std:: cout: 1e-40
  11. to_string: 0.000000
  12.  
  13. std:: cout: 1.23457e+08
  14. to_string: 123456789.000000

二、string转int


 
 
  1. #include <iostream>
  2. #include <string>
  3. int main()
  4. {
  5. std:: string str1 = "45";
  6. std:: string str2 = "3.14159";
  7. std:: string str3 = "31337 with words";
  8. std:: string str4 = "words and 2";
  9. int myint1 = std::stoi(str1);
  10. int myint2 = std::stoi(str2);
  11. int myint3 = std::stoi(str3);
  12. // 错误: 'std::invalid_argument'
  13. // int myint4 = std::stoi(str4);
  14. std:: cout << "std::stoi(\"" << str1 << "\") is " << myint1 << '\n';
  15. std:: cout << "std::stoi(\"" << str2 << "\") is " << myint2 << '\n';
  16. std:: cout << "std::stoi(\"" << str3 << "\") is " << myint3 << '\n';
  17. //std::cout << "std::stoi(\"" << str4 << "\") is " << myint4 << '\n';
  18. }

结果:

std::stoi("45") is 45
std::stoi("3.14159") is 3
std::stoi("31337 with words") is 31337

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值