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

在C++中,将string转换为int是常见的操作。有多种方法可以实现这一目标,选择合适的方式取决于你的编译器版本、错误处理需求以及性能要求。
使用 stoi 函数(推荐,C++11 及以上)
stoi 是 C++11 引入的便捷函数,用于将字符串直接转换为整数。它位于 头文件中。
示例代码:
#include #include 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
在较老的编译器或需要兼容旧标准时,可以使用 stringstream。这种方法更灵活,适合混合类型转换。
立即学习“C++免费学习笔记(深入)”;
示例代码:
#include #include #include 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 风格,简单但不安全)
atoi 来自 C 语言,需包含 。它接受 const char* 类型,因此要配合 c_str() 使用。
示例代码:
#include #include #include using namespace std;int main() { string str = "999"; int num = atoi(str.c_str()); cout << "结果:" << num << endl; return 0;}
缺点是:遇到非法输入时返回 0,无法判断是转换失败还是原始值就是 0,且不抛异常,不利于错误排查。仅适用于输入可信的场景。
其他相关转换函数
除了 stoi,C++ 还提供了更多类型转换函数:
stol:转为 long stoll:转为 long long stoul:转为 unsigned long stof / stod:转为 float / double
这些函数都支持起始位置偏移参数,例如:
size_t pos;int num = stoi("123abc", &pos); // pos 返回第一个非法字符的位置cout << "转换了 " << pos << " 个字符" << endl; // 输出 3
基本上就这些常用方法。日常开发中优先使用 stoi,兼顾简洁与安全性;需要兼容旧环境时可选 stringstream 或 atoi,但注意做好输入校验。
以上就是c++++怎么将string转换为int类型_c++字符串与整数类型转换技巧的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1485773.html
微信扫一扫
支付宝扫一扫