
if the value converted is out of range for integer data type, it returns INTMIN or INTMAX. This solution is slightly modified version of my another solution. To convert from string representation to integer value, we can use std::stringstream. Return negate ? result : -result //-result is positive! Result = result * 10 - (*s - '0') //assume negative number Throw std::invalid_argument("invalid input string") There are 5 significant methods to convert strings to numbers in C++ as follows: Using stoi () function Using atoi () function Using stringstream Using sscanf () function Using for Loop Using strtol () function 1. std::ostringstream can be used to convert any streamable type to a string representation, by inserting the object into a std::ostringstream object (with the. Throw std::invalid_argument("sign character only.") Throw std::invalid_argument("null or empty string argument") Here is one robust implemtation (untested though): int to_int(char const *s) So the safe and robust approach is to write your own function that parses the input string, and verify each character to check if it is digit or not, and then work accordingly. They will return 10 instead of notifying error. The stoi() function converts a string data to an integer type by passing the string as a parameter to return an integer value. Note that the above two approaches would fail for input s = "10jh".

Also if the string value can’t be represented as an valid int data type, then 0 is returned. Std::istringstream(s) > i //i is 10 after this To convert from string representation to integer value, we can use std::stringstream. In C++03/98, any of the following can be used: std::string s = "10" You can use std::stol or std:stoll though in case int seems too small for the input string. Note that std::stoi will throw exception of type std::invalid_argument if the conversion cannot be performed, or std::out_of_range if the conversion results in overflow(i.e when the string value is too big for int type).

In C++11, use std::stoi as: std::string s = "10"
