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.
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;
}
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
.
#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;
}
#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;
}
#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;
}
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;
}
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:
#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;
}