知识点6 C++数据类型转换 string
2024-09-02 13:22:40
一、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 << '\n';
std::cout << perfect << '\n';
return 0;
}
Output:
pi is 3.141593
28 is a perfect number
二、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) << "]\n";
std::cout << str_hex << ": " << i_hex << '\n';
std::cout << str_bin << ": " << i_bin << '\n';
std::cout << str_auto << ": " << i_auto << '\n'; return 0;
}
Output:
2001, A Space Odyssey: 2001 and [, A Space Odyssey]
40c3: 16579
-10010110001: -1201
0x7f: 127
最新文章
- .bat文件和Jar包的生成及运行
- Centos 压缩、解压和打包命令
- 将CachedRowSet中的数据转储到对象中
- 如何使用Android Studio开发/调试Android源码
- 从maya导入物体 Importing Objects From Maya
- javascript的变量、作用域和内存问题
- Linux系统编程(21)——信号的产生
- 关于Application Cache
- 【高德地图API】从零开始学高德JS API(三)覆盖物——标注|折线|多边形|信息窗口|聚合marker|麻点图|图片覆盖物
- js基础 2
- vue.js基础知识篇(1):简介、数据绑定
- angular学习笔记01
- spring AOP 和自定义注解进行身份验证
- 算法--java实现将数字转换成人民币大写(迅雷面试题)
- 学习笔记29—Linux基础
- Hibernnate 一对多多对一双向关联
- 使用Axure RP原型设计实践08,制作圆角文本框
- 50个必备jQuery代码段
- leetcode644. Maximum Average Subarray II
- oracle错误一览表
热门文章
- BAT公司职级体系及薪水解密
- docker 安装 apollo
- java8 List集合的排序,求和,取最大值,按照条件过滤
- Prometheus 监控目标运行状态并邮件通知
- DOM事件机制解惑(摘)--事件的传播机制
- ******可用 SpringBoot 项目打包分开lib,配置和资源文件
- layui 动态表格设置单元格样式
- c# 项目nuget不自动安装dll
- 二、NodeJS入门&mdash;&mdash;准备工作(2)&mdash;&mdash;MongoDB安装以及客户端Robomongo安装和使用
- C# 构造基础返回值类型-BaseResponse