c++size-tsize-type

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


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?


Solution

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