std::stoi最简洁但需异常处理;2. stringstream适合复杂转换;3. atoi兼容C但无错误提示;4. 手动实现灵活可控。根据需求选择方法。

在C++中,将string转换成int有多种方式,常用的方法包括使用标准库函数和手动实现。下面介绍几种常见且实用的实现方式。
std::stoi 是最简单直接的方法,它能将字符串转换为整数。
示例代码:#include <string>
#include <iostream>
<p>int main() {
std::string str = "12345";
int num = std::stoi(str);
std::cout << num << std::endl; // 输出 12345
return 0;
}
注意:如果字符串不是合法数字,会抛出 std::invalid_argument 或 std::out_of_range 异常,使用时建议加异常处理。
利用 stringstream 进行类型转换,适合需要格式控制或与其他类型混合转换的场景。
立即学习“C++免费学习笔记(深入)”;
示例代码:#include <sstream>
#include <string>
#include <iostream>
<p>int main() {
std::string str = "67890";
std::stringstream ss(str);
int num;
ss >> num;
if (ss.fail()) {
std::cout << "转换失败" << std::endl;
} else {
std::cout << num << std::endl;
}
return 0;
}
atoi 来自C语言标准库,需将 string 转为 C 风格字符串(c_str())。
#include <cstdlib>
#include <string>
#include <iostream>
<p>int main() {
std::string str = "42";
int num = std::atoi(str.c_str());
std::cout << num << std::endl;
return 0;
}
缺点是出错时不抛异常,仅返回0,难以判断是否转换成功。
适用于学习原理或限制环境下不使用标准库的情况。
示例代码:#include <string>
#include <iostream>
<p>int stringToInt(const std::string& str) {
int result = 0;
int sign = 1;
int i = 0;</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">if (str.empty()) return 0;
if (str[0] == '-' || str[0] == '+') {
sign = (str[0] == '-') ? -1 : 1;
i++;
}
for (; i < str.length(); ++i) {
if (str[i] < '0' || str[i] > '9') break;
result = result * 10 + (str[i] - '0');
}
return result * sign;}
int main() { std::string str = "-123"; int num = stringToInt(str); std::cout << num << std::endl; return 0; }
此方法可控制逻辑,比如跳过非法字符、处理符号等。
基本上就这些常见的C++字符串转整数方式。根据实际需求选择:追求简洁用 std::stoi,注重兼容性可用 stringstream 或手动实现。
以上就是c++++怎么把string转换成int_c++字符串转整数实现方式的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号