string和int之间的转换
#include<cstring>
std::string src_str = "1234";
int num = std::stoi(src_str);
int num1 = std::atoi(src_str.c_str());
std::string str = std::to_string(1234);
- stoi(const string& str),会做范围检查,默认范围是在int的范围内的,如果超出范围的话,则会runtime error!;
- atoi(const char* str),的参数是const char*,需要c_string()函数将string转换为char*,不会做范围检查,如果超出范围的话,超出上界,则输出上界,超出下界,则输出下界;
- to_string(int num)将整数转换为字符串;
- 将字符串转换为long使用stol(string s);
本文介绍了C++中字符串(string)与整数(int)之间的转换方法,包括stoi、atoi及to_string函数的用法及其特点。stoi进行范围检查,超出范围抛出异常;atoi不检查范围,越界返回边界值;to_string用于整数转字符串。

2909

被折叠的 条评论
为什么被折叠?



