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
相关推荐
j445566113 分钟前
C++中的职责链模式高级应用
开发语言·c++·算法
WarmSword22 分钟前
mac上用cursor/vscode调试root权限进程
c++·ide·vscode·macos·mac
m0_7369191034 分钟前
模板元编程性能分析
开发语言·c++·算法
wbs_scy1 小时前
C++11:类新功能、lambda与包装器实战
开发语言·c++
永远睡不够的入1 小时前
类和对象(中)
c++
飞鹰511 小时前
深度学习算子CUDA优化实战:从GEMM到Transformer—Week4学习总结
c++·人工智能·深度学习·学习·transformer
2301_765703141 小时前
C++中的职责链模式实战
开发语言·c++·算法
StandbyTime1 小时前
《算法笔记》学习记录-第一章
c++·算法·算法笔记
近津薪荼1 小时前
优选算法——双指针8(单调性)
数据结构·c++·学习·算法
f狐0狸x1 小时前
【C++修炼之路】C++ list容器基本用法详解
开发语言·c++·list