Why does the address of a "size_type" variable is used as an argument of "stoi()" in C++?

270 views Asked by At

The address of a size_type variable is used as an argument of stoi(). Reference link is given below:

stoi()

I can also do the same operation without using size_type. I have read the documentation I have given, but I didn't get when should I use it.

Then, what is the contribution of using the address of a size_type variable here and when sould we use it?

2

There are 2 answers

1
Yuri Nudelman On BEST ANSWER

First, it is not mandatory, it can be NULL. The contribution is for case when your string contains several values. This allows to parse them one by one. After a call to stoi, *idx will contain the start index of the next integer. For example:

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

EDIT: as @Surt correctly commented, some error handling can and should added here. So lets make this example complete. The function stoi can throw either invalid_argument or out_of_range, these exceptions should be handled. How to handle them - IDK, your decision here is an example:

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;
    }
}
0
anatolyg On

If your string contains more data than just a number, you can use idx to parse the rest of the data.

Another situation where this could be useful: if you want to ensure your string contains nothing but a number - you parse the number, look what appears afterwards, and if there is something, you throw an exception: something like 1234heh is not a valid number.