std::stoi最简单但需异常处理;2. stringstream兼容性好可检查完整转换;3. std::from_chars(C++17)高效无异常适合高性能场景;根据编译环境和需求选择合适方法。

在C++中,将std::string转换成int有多种方法,常用且安全的方式包括使用std::stoi、std::stringstream和std::from_chars(C++17起)。下面介绍几种实用的方法。
示例代码:
立即学习“C++免费学习笔记(深入)”;
#include <string>
#include <iostream>
<p>int main() {
std::string str = "123";
try {
int num = std::stoi(str);
std::cout << "转换结果: " << num << std::endl;
} catch (const std::invalid_argument& e) {
std::cerr << "错误:无法转换为整数" << std::endl;
} catch (const std::out_of_range& e) {
std::cerr << "错误:数值超出int范围" << std::endl;
}
return 0;
}
std::stoi会抛出异常,建议用try-catch处理。示例代码:
立即学习“C++免费学习笔记(深入)”;
#include <sstream>
#include <string>
#include <iostream>
<p>int main() {
std::string str = "456";
std::stringstream ss(str);
int num;</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">if (ss >> num && ss.eof()) {
std::cout << "转换成功: " << num << std::endl;
} else {
std::cerr << "转换失败" << std::endl;
}
return 0;}
优点是能检查是否完全转换(比如防止"123abc"被部分读取),通过eof()判断流结束位置。
示例代码:
立即学习“C++免费学习笔记(深入)”;
#include <charconv>
#include <string>
#include <iostream>
<p>int main() {
std::string str = "789";
int num;
auto [ptr, ec] = std::from_chars(str.data(), str.data() + str.size(), num);</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">if (ec == std::errc()) {
std::cout << "转换成功: " << num << std::endl;
} else {
std::cerr << "转换失败" << std::endl;
}
return 0;} 该方法速度快,适用于嵌入式或高频调用场景,但需要编译器支持C++17。
std::stoi,简洁易读。stringstream。std::from_chars。基本上就这些常用方式,选择合适的方法取决于你的项目需求和编译环境。
以上就是c++++中string怎么转换成int_c++ string转int方法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号