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
相关推荐
爱学习的小邓同学23 分钟前
c++ --- priority_queue的使用以及简单实现
c++
清朝牢弟2 小时前
Ubuntu系统VScode实现opencv(c++)视频的处理与保存
c++·人工智能·vscode·opencv·ubuntu
oioihoii2 小时前
在macOS上使用VS Code和Clang配置C++开发环境
c++·macos·策略模式
科大饭桶3 小时前
C++入门自学Day5-- C/C++内存管理(续)
c语言·开发语言·c++
lzb_kkk3 小时前
【实习总结】Qt通过Qt Linguist(语言家)实现多语言支持
开发语言·c++·qt·1024程序员节·qt linguist·qt 语言家
ZLRRLZ3 小时前
【数据结构】哈希表实现
数据结构·c++·散列表
weixin_307779134 小时前
ClickHouse Windows迁移方案与测试
linux·c++·数据仓库·windows·clickhouse
老猿讲编程4 小时前
LCM中间件入门(1):工作原理核心概念及Ubuntu环境下的C++实践
c++·ubuntu·中间件·lcm
爱掉发的小李5 小时前
Linux 环境下 Docker 安装与简单使用指南
java·linux·运维·c++·python·docker·php
澄澈i6 小时前
设计模式学习[17]---组合模式
c++·学习·设计模式·组合模式