C++中string转int常用方法有三种:①std::stoi,简单直接但需处理异常;②std::stringstream,兼容性好可精确控制解析过程;③std::from_chars(C++17),无异常高性能适合性能敏感场景。

在C++中,将std::string转换为int类型有多种方法,常用且安全的方式包括使用std::stoi、std::stringstream以及std::from_chars(C++17起)。下面介绍这些实现方式及其使用场景。
std::stoi 是最直接的方法,定义在 <string> 头文件中,能将字符串转换为整数。
示例代码:
#include <string><br>#include <iostream><br><br>int main() {<br> std::string str = "12345";<br> try {<br> int num = std::stoi(str);<br> std::cout << "转换结果: " << num << std::endl;<br> } catch (const std::invalid_argument& e) {<br> std::cerr << "错误:无法转换为整数" << std::endl;<br> } catch (const std::out_of_range& e) {<br> std::cerr << "错误:数值超出 int 范围" << std::endl;<br> }<br> return 0;<br>}
注意:当字符串格式不合法或数值超出int表示范围时,std::stoi会抛出异常,需用try-catch处理。
立即学习“C++免费学习笔记(深入)”;
利用std::stringstream进行类型转换,适合需要兼容旧标准或复杂输入解析的场景。
#include <sstream><br>#include <string><br>#include <iostream><br><br>int main() {<br> std::string str = "6789";<br> std::stringstream ss(str);<br> int num;<br> if (ss >> num && ss.eof()) {<br> std::cout << "转换成功: " << num << std::endl;<br> } else {<br> std::cerr << "转换失败:字符串格式无效" << std::endl;<br> }<br> return 0;<br>}
说明:ss.eof() 确保整个字符串都被读取,防止如 "123abc" 这类部分匹配的情况被误判为成功。
这是C++17引入的高效无异常方法,适用于对性能要求较高的场合。
#include <string><br>#include <charconv><br>#include <iostream><br><br>int main() {<br> std::string str = "42";<br> int num;<br> auto [ptr, ec] = std::from_chars(str.data(), str.data() + str.size(), num);<br><br> if (ec == std::errc()) {<br> std::cout << "转换成功: " << num << std::endl;<br> } else {<br> std::cerr << "转换失败" << std::endl;<br> }<br> return 0;<br>}
优点:不抛异常、速度快、可指定进制(如二进制、十六进制),适合嵌入式或高性能应用。
基本上就这些常用方法。根据项目需求选择:简单场景用std::stoi,需控制异常时用stringstream,追求性能且支持C++17以上推荐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号