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
相关推荐
王维同学2 小时前
[自学][Windows C++]RunOnceEx 注册表分组键的安全遍历
c++·windows·安全·开源
Scott9999HH3 小时前
告别流量波动玄学!从法拉第电磁定律到底层 C/C++ 流量累积算法,深度解密工业级电磁流量计选型与开发
c语言·c++·算法
脱胎换骨-军哥3 小时前
C++/Rust无缝互操作:混合系统新常态
开发语言·c++·rust
旖-旎5 小时前
LeetCode 279:完全平方数(完全背包)—— 题解
c++·算法·leetcode·动态规划·背包问题
胖大和尚6 小时前
C++ 多线程编程的实现方式
c++·thread
在水一缸7 小时前
深入浅出 Catch2:现代 C++ 测试框架的优雅实践
开发语言·c++·单元测试·log4j·测试框架·catch2
2401_841495647 小时前
【数据结构】B*树
数据结构·c++·b树·算法·删除·插入·三分分裂
斐夷所非8 小时前
在纷繁竞逐中稳步前行:C++ 2006–2020
c++
保持清醒5409 小时前
类和对象上
c++
乱七八糟的屋子9 小时前
Poco C++高级实战教程:线程池+日志系统+加密算法+WebSocket长连接
c++·websocket·加密解密·#poco·#c++高级开发