C++ String to Integer Conversion

Well, I can see some logical issues with your code.
Can you try this code and confirm wether it is working or not.

#include <iostream>
#include <string>
#include <stdexcept> // Include this for std::invalid_argument and std::out_of_range

int main() {
    std::string str = "12345"; // This could be any numeric string.

    int num = 0; // The converted integer will be stored here.

    try {
        num = std::stoi(str);
        std::cout << "Converted integer: " << num << std::endl;
    } 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;
}

Thanks

4 Likes