C++中string转int常用方法包括:①推荐使用C++11的stoi函数,支持异常处理;②stringstream适用于旧标准,灵活性高;③atoi为C风格函数,简单但不安全。优先选择stoi以兼顾安全性与简洁性。

在C++中,将string转换为int是常见的操作。有多种方法可以实现这一目标,选择合适的方式取决于你的编译器版本、错误处理需求以及性能要求。
stoi 是 C++11 引入的便捷函数,用于将字符串直接转换为整数。它位于 <string> 头文件中。
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "1234";
int num = stoi(str);
cout << "转换结果:" << num << endl;
return 0;
}
如果字符串包含非法字符(如 "abc" 或 "12a3"),stoi 会抛出 invalid_argument 异常;如果数值超出 int 范围,则抛出 out_of_range 异常。建议配合 try-catch 使用:
try {
int num = stoi("not_a_number");
} catch (const invalid_argument& e) {
cout << "无效参数:" << e.what() << endl;
} catch (const out_of_range& e) {
cout << "数值越界:" << e.what() << endl;
}
在较老的编译器或需要兼容旧标准时,可以使用 stringstream。这种方法更灵活,适合混合类型转换。
立即学习“C++免费学习笔记(深入)”;
示例代码:#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main() {
string str = "5678";
stringstream ss(str);
int num;
if (ss >> num) {
cout << "转换成功:" << num << endl;
} else {
cout << "转换失败" << endl;
}
return 0;
}
注意:若字符串开头有空格,>> 操作符会自动跳过;但如果中间或开头有非数字字符,可能导致转换不完整或失败。
atoi 来自 C 语言,需包含 <cstdlib>。它接受 const char* 类型,因此要配合 c_str() 使用。
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
int main() {
string str = "999";
int num = atoi(str.c_str());
cout << "结果:" << num << endl;
return 0;
}
缺点是:遇到非法输入时返回 0,无法判断是转换失败还是原始值就是 0,且不抛异常,不利于错误排查。仅适用于输入可信的场景。
除了 stoi,C++ 还提供了更多类型转换函数:
这些函数都支持起始位置偏移参数,例如:
size_t pos;
int num = stoi("123abc", &pos); // pos 返回第一个非法字符的位置
cout << "转换了 " << pos << " 个字符" << endl; // 输出 3
基本上就这些常用方法。日常开发中优先使用 stoi,兼顾简洁与安全性;需要兼容旧环境时可选 stringstream 或 atoi,但注意做好输入校验。
以上就是c++++怎么将string转换为int类型_c++字符串与整数类型转换技巧的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号