【问题标题】:Why does the address of a "size_type" variable is used as an argument of "stoi()" in C++?为什么“size_type”变量的地址在 C++ 中用作“stoi()”的参数?
【发布时间】:2021-02-16 03:51:58
【问题描述】:

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

stoi()

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

那么,这里使用 size_type 变量的地址有什么作用,什么时候使用呢?

【问题讨论】:

  • 您是否尝试过阅读您链接的文档?如果不为 NULL,“idx 是指向 size_t 类型对象的指针,其值由函数设置为 str 中数值后下一个字符的位置。”
  • 我阅读了文档,但我不知道什么时候应该使用它。
  • 阅读here
  • @NathanOliver 我不知道什么时候应该使用它。你能用一个例子简单地解释一下吗?

标签: c++ size-t size-type


【解决方案1】:

首先,它不是强制性的,它可以是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;
    }
}

【讨论】:

  • 很好,您可以通过一些错误处理来增强它。
【解决方案2】:

如果您的字符串包含比数字更多的数据,您可以使用idx 来解析其余数据。

这可能有用的另一种情况:如果你想确保你的字符串只包含一个数字 - 你解析数字,看看之后出现的内容,如果有什么,你抛出一个异常:像1234heh不是有效数字。

【讨论】:

    猜你喜欢
    • 2017-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-26
    • 2021-08-06
    • 1970-01-01
    相关资源
    最近更新 更多