gpt4 book ai didi

c++ - 为什么在 C++ 中将 "size_type"变量的地址用作 "stoi()"的参数?

转载 作者:行者123 更新时间:2023-12-03 07:07:06 25 4
gpt4 key购买 nike

size_type 变量的地址用作 stoi() 的参数。引用链接如下:

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_argumentout_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;
}
}

关于c++ - 为什么在 C++ 中将 "size_type"变量的地址用作 "stoi()"的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64663355/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com