stoi()函数
stoi()函数是C++11标准中引入的一个新函数,用于将字符串转换为整数。它的名称是"string to integer"的缩写,意为"字符串到整数"的转换。
stoi()函数的原型如下:
cpp
int stoi(const string& str, size_t* pos = 0, int base = 10);
其中,str是要转换的字符串,pos是一个可选参数,用于指定转换的起始位置,base是转换的基数,默认为10进制。
下面是一个使用stoi()函数的简单示例:
cpp
#include <iostream>
#include <string>
int main() {
std::string str = "12345";
int num = std::stoi(str);
return 0;
}
需要注意的是,stoi()函数在转换过程中会检查字符串的有效性。如果字符串中包含非数字字符(除了可能的正负号和基数指定的字符外),或者转换结果超出了int类型的表示范围,stoi()函数将抛出std::invalid_argument或std::out_of_range异常。因此,在使用stoi()函数时,最好使用异常处理机制来确保程序的健壮性。
to_string()函数
与
stoi()函数相对应,to_string()函数用于将整数(或其他数值类型)转换为字符串。它的名称是"to string"的缩写,意为"到字符串"的转换。
to_string()函数有多个重载版本,可以处理不同类型的输入。对于整数类型,它的原型如下:
string to_string(int value);
其中,value是要转换的整数。
下面是一个使用to_string()函数的简单示例:
cpp
#include <iostream>
#include <string>
int main() {
int num = 12345;
std::string str = std::to_string(num);
return 0;
}
与stoi()函数相比,to_string()函数的使用相对简单,因为它不需要处理复杂的转换规则和异常情况。只要输入的数值在有效范围内,to_string()函数就能成功地将其转换为字符串。
其他相关函数
除了stoi()和to_string()函数外,C++标准库还提供了其他一些用于类型转换的函数,例如:
stof()、stod()、stold():分别用于将字符串转换为float、double和long double类型的浮点数。to_wstring()、to_u16string()、to_u32string():分别用于将数值转换为宽字符字符串、UTF-16字符串和UTF-32字符串。