C++ stoi(): Convert a String to an Integer (With Examples)
This Snippet is coded by a user inOnline cpp Compiler. You can see and run this code too.
زبان: C++
std::stoi (string to integer) parses a numeric string and returns an int. Its common form is std::stoi(str, pos, base). The input is a std::string; pos is an optional std::size_t* that receives the index of the first unconverted character, and base selects the numeric base (2–36, or 0 for auto-detection). The function skips leading whitespace, accepts an optional + or - sign, and reads digits until a non-digit is found. If no conversion can be performed, it throws std::invalid_argument; if the value exceeds int range, it throws std::out_of_range. The return value is the parsed integer. For example, std::stoi("12345") returns 12345, while std::stoi("42abc", &pos) returns 42 and sets pos to 2. Because it stops at the first character that cannot be part of a valid number, std::stoi("12x") returns 12; if strict full-string validation is needed, compare pos with the original string length. Use try/catch to handle malformed input and overflow safely. Time complexity is O(n) in the length of the parsed prefix, and extra space is O(1). It is a convenient, standard C++11 approach for converting strings to integers.