gpt-4.1-mini-2025-04-14· OpenAI
WildChat-4.8M (AI2)
c++ cast string to int
- User
c++ cast string to int
- Assistant
In C++, there are several ways to convert a
std::stringto anint. Here are some common methods:1.
std::stoi(C++11 and later)cpp#include <iostream> #include <string> int main() { std::string str = "12345"; int num = std::stoi(str); std::cout << num << std::endl; // Output: 12345 return 0; }- Throws
std::invalid_argumentif the string is not a valid number. - Throws
std::out_of_rangeif the number is out ofintrange.
2.
std::stringstreamcpp - Throws