[数字] 转换 “字符串”(int -> string)
【头文件】
#include <string>
- 注意这个是string,不是cstring
- 从C++11开始引入
【函数名】
to_string()
std::to_string(int)
std::to_string(long)
std::to_string(long long)
std::to_string(float)
std::to_string(double)
std::to_string(long double)
转换时保留负号
还支持各类unsigned,基本上主流数值类型都能无脑转换。
“字符串” 转换 [数字](string -> int)
【头文件】
#include <cstdlib>
标准库函数,但是使用时一般会配合
#include <string>
【函数名】
stoi()
对应 int
stol()
对应 long
stoll()
对应 long long
std::stoi(string)
std::stol(string)
std::stoll(string)
stoi
会自动将string
数值部分的首位0
消去,同时还会保留负号
例如stoi("00123abc")
,结果为123
,自动消去首位无效0
stoi("-0123")
,结果为-123
。