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
相关推荐
小丑西瓜6664 小时前
CMake基础用法,cmake_minimum_required,project,add_executable
linux·服务器·c++·camke
晚风吹长发4 小时前
初步了解Linux中的命名管道及简单应用和简单日志
linux·运维·服务器·开发语言·数据结构·c++·算法
fpcc4 小时前
设计心得——隔离隐藏的初步实践
c++
C++ 老炮儿的技术栈5 小时前
不调用C++/C的字符串库函数,编写函数strcpy
c语言·开发语言·c++·windows·git·postman·visual studio
fyzy5 小时前
C++写后端实现,实现前后端分离
开发语言·c++
CSDN_RTKLIB6 小时前
C++谓词
c++·stl
汉克老师7 小时前
GESP2025年9月认证C++五级真题与解析(单选题9-15)
c++·算法·贪心算法·排序算法·归并排序·gesp5级·gesp五级
飞鹰517 小时前
CUDA高级优化实战:Stream、特殊内存与卷积优化—Week3学习总结
c++·gpt·chatgpt·gpu算力
txinyu的博客8 小时前
std::function
服务器·开发语言·c++
学嵌入式的小杨同学9 小时前
【嵌入式 C 语言实战】交互式栈管理系统:从功能实现到用户交互全解析
c语言·开发语言·arm开发·数据结构·c++·算法·链表