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
相关推荐
hweiyu007 分钟前
C++设计模式,高级开发,算法原理实战,系统设计与实战(视频教程)
c++·算法·设计模式
十年编程老舅35 分钟前
‌C++左值与右值:从基础概念到核心应用‌
linux·c++·右值引用·c++17·c++左值·c++右值·左值引用
John_ToDebug1 小时前
Chrome性能黑魔法:深入浅出PGO优化与实战指南
c++·chrome
和光同尘 、Y_____1 小时前
BRepMesh_IncrementalMesh 重构生效问题
c++·算法·图形渲染
起个名字费劲死了2 小时前
手眼标定之已知同名点对,求解转换RT,备份记录
c++·数码相机·机器人·几何学·手眼标定
雅雅姐2 小时前
C++中的单例模式的实现
c++
lingran__2 小时前
速通ACM省铜第一天 赋源码(The Cunning Seller (hard version))
c++·算法
沐怡旸3 小时前
【基础知识】仿函数与匿名函数对比
c++·面试
LoveXming4 小时前
Chapter4—工厂方法模式
c++·设计模式·简单工厂模式·工厂方法模式·开闭原则
青草地溪水旁4 小时前
设计模式(C++)详解—工厂方法模式(2)
c++·工厂方法模式