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++·qt
风清扬_jd3 小时前
Chromium 如何定义一个chrome.settingsPrivate接口给前端调用c++
前端·c++·chrome
Death2004 小时前
Qt 6 相比 Qt 5 的主要提升与更新
开发语言·c++·qt·交互·数据可视化
麻辣韭菜6 小时前
网络基础 【HTTP】
网络·c++·http
阿史大杯茶6 小时前
Codeforces Round 976 (Div. 2 ABCDE题)视频讲解
数据结构·c++·算法
转调7 小时前
每日一练:地下城游戏
开发语言·c++·算法·leetcode
wdxylb7 小时前
使用C++的OpenSSL 库实现 AES 加密和解密文件
开发语言·c++·算法
CSP126368 小时前
特别节目————集训总结
c++
程序猿阿伟8 小时前
《C++游戏人工智能开发:开启智能游戏新纪元》
c++·人工智能·游戏
一线青少年编程教师8 小时前
线性表三——队列queue
数据结构·c++·算法