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
相关推荐
T0uken4 分钟前
基于 vcpkg 与 LLVM-MinGW 的 Qt6 静态链接开发方案
c++·windows·qt
睡一觉就好了。6 分钟前
C++11(一)
c++
水云桐程序员23 分钟前
C++的主要应用场景
c++·学习方法
叼烟扛炮1 小时前
C++第一讲:C++ 入门基础
开发语言·c++·函数重载·引用·内联函数·nullptr
zh_xuan2 小时前
使用libcurl调用http接口
c++·github·libcurl
zh路西法2 小时前
【RDKX5多摄像头模型推理】USB带宽限制与ROS2话题零拷贝转发
linux·c++·python·深度学习
千寻girling2 小时前
五一劳动节快乐 [特殊字符][特殊字符][特殊字符]
java·c++·git·python·学习·github·php
汉克老师3 小时前
GESP2025年3月认证C++五级( 第一部分选择题(9-15))
c++·算法·高精度计算·二分算法·gesp5级·gesp五级
迷途之人不知返3 小时前
stack和queue的学习与模拟实现
c++
汉克老师4 小时前
GESP2025年3月认证C++五级( 第二部分判断题(1-10))
c++·算法·分治算法·线性筛法·gesp5级·gesp五级