c++ - 为什么“size_type”变量的地址在 C++ 中用作“stoi()”的参数?
问题描述
size_type变量的地址用作stoi()的参数。参考链接如下:
我也可以在不使用size_type的情况下执行相同的操作。我已经阅读了我提供的文档,但我不知道什么时候应该使用它。
那么,在这里使用size_type变量的地址以及何时使用它的贡献是什么?
解决方案
首先,它不是强制性的,它可以是NULL。该贡献适用于您的字符串包含多个值的情况。这允许一个一个地解析它们。调用 stoi 后,*idx 将包含下一个整数的开始索引。例如:
int main() {
std::string str = "23 45 56 5656";
std::string::size_type off = 0;
do {
std::string::size_type sz;
cout << std::stoi(str.substr(off), &sz) << endl;
off += sz;
} while (off < str.length());
}
// will print
// 23
// 45
// 56
// 5656
编辑:正如@Surt 正确评论的那样,可以而且应该在此处添加一些错误处理。所以让我们完成这个例子。函数 stoi 可以抛出invalid_argument
或out_of_range
,这些异常应该被处理。如何处理它们 - IDK,你的决定是一个例子:
int main() {
std::string str = "23 45 56 5656 no int";
std::string::size_type off = 0;
try {
do {
std::string::size_type sz;
std:cout << std::stoi(str.substr(off), &sz) << std::endl;
off += sz;
} while (off < str.length());
} catch(const std::invalid_argument &e) {
std::cout << "Oops, string contains something that is not a number"
<< std::endl;
} catch(const std::out_of_range &e) {
std::cout << "Oops, some integer is too long" << std::endl;
}
}
推荐阅读
- go - 单例实例不断在 Go 中创建新实例
- css - 如何根据子级高度调整固定高度的父级 div?
- matlab - 如何在 Matlab 中使用带有棋盘图像的相机校准来获得以毫米为单位的像素大小?
- jekyll - Jekyll 站点帖子和液体命令连接错误
- socket.io - 套接字 io CORS 被阻止
- plotly-dash - 如何在不使用字典的情况下更新数据表行
- benchmarking - 用于测量速度和内存消耗的与语言无关的基准测试工具
- google-sheets - 从 Google 电子表格获取动态范围
- haskell - 如何从类型中获取价值
- mongodb - MongoRepository @Query 无法将字符串解析为日期