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
相关推荐
神仙别闹3 小时前
基于QT(C++)实现学本科教务系统(URP系统)
数据库·c++·qt
deng-c-f3 小时前
Linux C/C++ 学习日记(49):线程池
c++·学习·线程池
ulias2123 小时前
C++ 的容器适配器——从stack/queue看
开发语言·c++
daidaidaiyu4 小时前
FFmpeg 关键的结构体
c++·ffmpeg
欧特克_Glodon4 小时前
C++医学图像处理经典ITK库用法详解<一>:图像输入输出模块功能
c++·图像处理·itk
一个不知名程序员www5 小时前
算法学习入门---priority_queue(C++)
c++·算法
Pafey6 小时前
C++的左值引用、右值引用以及转发和完美转发
c++
CoderCodingNo6 小时前
【GESP】C++三级真题 luogu-B4414 [GESP202509 三级] 日历制作
开发语言·c++·算法
晨曦夜月6 小时前
笔试强训day7
开发语言·c++·算法
木心爱编程7 小时前
【Qt 5.14.2 新手实战】QTC++入门筑基——按钮与标签联动:QPushButton + QLabel 实现图片切换器
java·c++·qt