The stoi function in C++ is a convenient way to convert a string to an integer. It can handle different numerical bases, which is particularly useful in competitive programming. Let's explore stoi and its various uses, including conversion from strings in different bases.

Basic Usage of stoi

The stoi function converts a string to an integer. By default, it assumes the string is in base 10.

#include <iostream>
#include <string>

int main() {
    std::string str = "123";
    int num = std::stoi(str);
    std::cout << num; // Output: 123
    return 0;
}

Using Different Bases

The stoi function can also convert strings that represent numbers in different bases (e.g., binary, octal, hexadecimal). You can specify the base as the third argument to stoi.

Binary (Base 2)

#include <iostream>
#include <string>

int main() {
    std::string binaryStr = "1011"; // Binary for 11
    int num = std::stoi(binaryStr, nullptr, 2);
    std::cout << num; // Output: 11
    return 0;
}

Octal (Base 8)

#include <iostream>
#include <string>

int main() {
    std::string octalStr = "17"; // Octal for 15
    int num = std::stoi(octalStr, nullptr, 8);
    std::cout << num; // Output: 15
    return 0;
}

Hexadecimal (Base 16)

#include <iostream>
#include <string>

int main() {
    std::string hexStr = "1A"; // Hexadecimal for 26
    int num = std::stoi(hexStr, nullptr, 16);
    std::cout << num; // Output: 26
    return 0;
}

Handling Invalid Inputs

When using stoi, you should be aware of potential invalid inputs. stoi will throw an std::invalid_argument exception if the input string cannot be converted to an integer, and an std::out_of_range exception if the resulting value is outside the range of representable values for an int.

#include <iostream>
#include <string>
#include <exception>

int main() {
    std::string str = "abc"; // Invalid input

    try {
        int num = std::stoi(str);
    } catch (const std::invalid_argument& e) {
        std::cerr << "Invalid argument: " << e.what() << std::endl;
    } catch (const std::out_of_range& e) {
        std::cerr << "Out of range: " << e.what() << std::endl;
    }

    return 0;
}

Converting from Different Bases to Decimal

In competitive programming, you might encounter problems where you need to convert numbers from one base to another. Here's how you can use stoi to handle such conversions:

Binary to Decimal

#include <iostream>
#include <string>

int binaryToDecimal(const std::string& binaryStr) {
    return std::stoi(binaryStr, nullptr, 2);
}

int main() {
    std::string binaryStr = "1101"; // Binary for 13
    int decimal = binaryToDecimal(binaryStr);
    std::cout << decimal; // Output: 13
    return 0;
}

Octal to Decimal