C++中stoi函数的第二个参数是什么?如何使用及示例?
C++ stoi函数第二个参数详解及示例
stoi的第二个参数是可选的size_t类型指针,核心作用是记录转换过程中第一个无法被解析为数字的字符在原字符串中的索引位置。如果不需要这个位置信息,可以传nullptr或者直接省略该参数(C++11及以后支持)。
下面是几个不同场景的示例,清晰展示该参数的作用差异:
场景1:字符串全为有效数字
#include <iostream> #include <string> int main() { std::string str = "1234"; size_t idx; int num = std::stoi(str, &idx); std::cout << "转换结果:" << num << "\n"; std::cout << "第一个未转换字符的索引:" << idx << "\n"; return 0; }
输出:
转换结果:1234 第一个未转换字符的索引:4
说明:所有字符都被成功转换,idx指向字符串末尾(索引等于字符串长度)。
场景2:字符串包含有效数字+非数字后缀
#include <iostream> #include <string> int main() { std::string str = "123abc45"; size_t idx; int num = std::stoi(str, &idx); std::cout << "转换结果:" << num << "\n"; std::cout << "第一个未转换字符的索引:" << idx << "\n"; std::cout << "未转换的剩余字符:" << str.substr(idx) << "\n"; return 0; }
输出:
转换结果:123 第一个未转换字符的索引:3 未转换的剩余字符:abc45
说明:stoi转换到第一个非数字字符'a'时停止,idx记录该字符的索引,你可以用这个索引处理剩余的字符串内容。
场景3:字符串开头为非数字(转换失败)
#include <iostream> #include <string> #include <stdexcept> int main() { std::string str = "abc123"; size_t idx; try { int num = std::stoi(str, &idx); std::cout << "转换结果:" << num << "\n"; } catch (const std::invalid_argument& e) { std::cout << "转换失败:" << e.what() << "\n"; std::cout << "第一个未转换字符的索引:" << idx << "\n"; } return 0; }
输出:
转换失败:invalid stoi argument 第一个未转换字符的索引:0
说明:因为没有找到任何可转换的数字,stoi抛出invalid_argument异常,此时idx保持为0,说明从字符串起始位置就无法解析。
场景4:不需要记录位置(省略第二个参数)
#include <iostream> #include <string> int main() { std::string str = "456xyz"; int num = std::stoi(str); // 省略第二个参数,不获取索引 std::cout << "转换结果:" << num << "\n"; return 0; }
输出:
转换结果:456
说明:如果只需要提取字符串开头的有效数字,不需要处理剩余内容,直接省略第二个参数即可。
内容的提问来源于stack exchange,提问作者VALIVETI SWAMY NAGA SAI NIVAS
相关产品推荐
相关产品推荐

