C++中的字符转换 to_string、sto

1.数字转字符串 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);

cpp 复制代码
int i = 10086;
double d = 3.1415926;
string s1 = to_string(i);
string s2 = to_string(d);
cout << s1 << endl;//10086
cout << s2 << endl;//3.1415926

2.字符串转数字 sto

将字符串转换为数字

参数:

str是需要转换的字符串;idx是需要转换的起始位置;base是确定转换为多少进制数

int stoi(const string & str, size_t * idx = 0, int base = 10);

long stol(const string & str, size_t * idx = 0, int base = 10);

unsigned long stoul(const string & str, size_t * idx = 0, int base = 10);

long long stoll(const string & str, size_t * idx = 0, int base = 10);

unsigned long long stoull(const string & str, size_t * idx = 0, int base = 10);

float stof(const string & str, size_t * idx = 0);

double stod(const string & str, size_t * idx = 0);

long double stold(const string & str, size_t * idx = 0);

cpp 复制代码
string s1("10086");
int i = stoi(s1);
cout << i << endl;//10086

string s2("3.1415926");
double d = stod(s2);
cout << s2 << endl;//3.1415926
相关推荐
虾球xz30 分钟前
游戏引擎学习第294天:增加手套
c++·学习·游戏引擎
龙湾开发1 小时前
计算机图形学编程(使用OpenGL和C++)(第2版)学习笔记 13.几何着色器(二)爆炸效果&修改图元类型
c++·笔记·学习·3d·图形渲染·着色器
ALex_zry1 小时前
C++ Kafka客户端(cppkafka)安装与问题解决指南
开发语言·c++·kafka
黑牛先生1 小时前
C++ 回调函数
开发语言·c++
laimaxgg1 小时前
高并发内存池|二、Common
c++·性能优化
June`2 小时前
专题五:floodfill算法(太平洋大西洋水流问题)
c++·算法·leetcode·深度优先·剪枝
yanjiee3 小时前
Cursor无法使用C/C++调试的解决办法
c语言·开发语言·c++·vscode
爱吃涮毛肚的肥肥(暂时吃不了版)3 小时前
仿腾讯会议——添加音频
c++·算法·面试·职场和发展·音视频·腾讯会议
学习使我变快乐3 小时前
C++:单例模式
开发语言·c++·单例模式
梁辰兴3 小时前
数据结构实验10.1:内部排序的基本运算
数据结构·c++·算法·排序算法·c·内部排序