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
相关推荐
And_Ii6 小时前
LCR 168. 丑数
c++
CoderMeijun7 小时前
C++ 时间处理与格式化输出:从 Linux 时间函数到 Timestamp 封装
c++·printf·stringstream·时间处理·clock_gettime
tankeven11 小时前
HJ176 【模板】滑动窗口
c++·算法
OxyTheCrack11 小时前
【C++】一文详解C++智能指针自定义删除器(以Redis连接池为例)
c++·redis
whitelbwwww11 小时前
C++基础--类型、函数、作用域、指针、引用、文件
开发语言·c++
leaves falling11 小时前
C/C++ const:修饰变量和指针的区别(和引用底层关系)
c语言·开发语言·c++
tod11311 小时前
深入解析ext2文件系统架构
linux·服务器·c++·文件系统·ext
不想写代码的星星11 小时前
C++ 类型萃取:重生之我在幼儿园修炼类型学
c++
比昨天多敲两行12 小时前
C++11新特性
开发语言·c++
xiaoye-duck12 小时前
【C++:C++11】核心特性实战:详解C++11列表初始化、右值引用与移动语义
开发语言·c++·c++11