博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C++string与int的相互转换(使用C++11)
阅读量:4580 次
发布时间:2019-06-09

本文共 1988 字,大约阅读时间需要 6 分钟。

一、int转string

#include 
#include
int main() { double f = 23.43; double f2 = 1e-9; double f3 = 1e40; double f4 = 1e-40; double f5 = 123456789; std::string f_str = std::to_string(f); std::string f_str2 = std::to_string(f2); // 注意:返回 "0.000000" std::string f_str3 = std::to_string(f3); // 注意:不返回 "1e+40". std::string f_str4 = std::to_string(f4); // 注意:返回 "0.000000" std::string f_str5 = std::to_string(f5); std::cout << "std::cout: " << f << '\n' << "to_string: " << f_str << "\n\n" << "std::cout: " << f2 << '\n' << "to_string: " << f_str2 << "\n\n" << "std::cout: " << f3 << '\n' << "to_string: " << f_str3 << "\n\n" << "std::cout: " << f4 << '\n' << "to_string: " << f_str4 << "\n\n" << "std::cout: " << f5 << '\n' << "to_string: " << f_str5 << '\n';}

输出

std::cout: 23.43to_string: 23.430000 std::cout: 1e-09to_string: 0.000000 std::cout: 1e+40to_string: 10000000000000000303786028427003666890752.000000 std::cout: 1e-40to_string: 0.000000 std::cout: 1.23457e+08to_string: 123456789.000000

二、string转int

#include 
#include
int main(){ std::string str1 = "45"; std::string str2 = "3.14159"; std::string str3 = "31337 with words"; std::string str4 = "words and 2"; int myint1 = std::stoi(str1); int myint2 = std::stoi(str2); int myint3 = std::stoi(str3); // 错误: 'std::invalid_argument' // int myint4 = std::stoi(str4); std::cout << "std::stoi(\"" << str1 << "\") is " << myint1 << '\n'; std::cout << "std::stoi(\"" << str2 << "\") is " << myint2 << '\n'; std::cout << "std::stoi(\"" << str3 << "\") is " << myint3 << '\n'; //std::cout << "std::stoi(\"" << str4 << "\") is " << myint4 << '\n';}

结果:

std::stoi("45") is 45

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

 

转载于:https://www.cnblogs.com/lizhenghao126/p/11053624.html

你可能感兴趣的文章
实验室的毕业照
查看>>
核心编程答案(第六章)
查看>>
Spring 3.x jar 包详解 与 依赖关系
查看>>
java线程详解二
查看>>
Jzoj4625 树
查看>>
maven项目导入依赖jar包并打包为可运行的jar包
查看>>
leecode第二十三题(合并K个排序链表)
查看>>
关于Eclipse的unsupported major minor version 51.0 错误
查看>>
2014年目标
查看>>
AT指令对串口CDMA短信设备发送短信
查看>>
weblogic启动后 登陆控制台特别慢的问题
查看>>
Spring加载resource时classpath*:与classpath:的区别
查看>>
雅虎股票接口
查看>>
映射“DataAdapter.TableMappings”
查看>>
Vue双向绑定
查看>>
activity生命周期
查看>>
IO流
查看>>
动画学习之Music图形绘制
查看>>
2019 2.15模拟赛
查看>>
扩展欧几里得
查看>>