推荐使用std::stoi进行string转int,C++11引入,支持异常处理;2. stringstream兼容性好,适合多类型转换;3. atoi来自C语言,失败返回0,不推荐高要求场景;4. 其他类型可用stol、stoll等;5. int转string推荐to_string或stringstream。

在C++中,将string转为int是常见的操作。最常用的方法有几种,每种适用于不同场景,下面详细介绍string转int的方式,以及字符串与数值类型相互转换的完整方法。
1. 使用 std::stoi
std::stoi(string to integer)是C++11引入的便捷函数,能将字符串直接转为int类型。
示例:
#include
#include iostream>
int main() {
std::string str = "12345";
int num = std::stoi(str);
std::cout
return 0;
}
注意:如果字符串无法转换(如包含非法字符),会抛出 std::invalid_argument 或 std::out_of_range 异常,建议用try-catch处理。
2. 使用 stringstream
这是较传统但兼容性好的方式,适合老标准或需要同时处理多种类型的场景。
立即学习“C++免费学习笔记(深入)”;
示例:
#include
#include
#include
int main() {
std::string str = "67890";
std::stringstream ss(str);
int num;
ss >> num;
std::cout
return 0;
}
优点是可链式读取多个值,也支持浮点、十六进制等格式。
3. 使用 atoi
atoi 来自C语言,需包含
#include
#include
int main() {
std::string str = "42";
int num = std::atoi(str.c_str());
return 0;
}
缺点是失败时返回0,无法区分"0"和非法输入,不推荐用于健壮性要求高的程序。
4. 其他数值类型转换参考
除了int,C++还提供类似函数转换其他类型:
- std::stol:转 long
- std::stoll:转 long long
- std::stof:转 float
- std::stod:转 double
用法与 stoi 相同,只需替换函数名。
5. 数值转字符串的方法
反过来,将int转string也有多种方式:
-
std::to_string:最简单,C++11起支持
std::string s = std::to_string(123); -
stringstream:
std::stringstream ss; ss
基本上就这些常见用法。推荐优先使用 std::stoi 和 std::to_string,简洁且安全。遇到异常情况记得加异常处理。转换不复杂,但细节决定稳定性。










