首页 > 解决方案 > 为什么“size_type”变量的地址在 C++ 中用作“stoi()”的参数?

问题描述

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

stoi()

我也可以在不使用size_type的情况下执行相同的操作。我已经阅读了我提供的文档,但我不知道什么时候应该使用它。

那么,在这里使用size_type变量的地址以及何时使用它的贡献是什么?

标签: c++size-tsize-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;
    }
}

推荐阅读