Posted on February 1, 2010 by kturley /* * A function to convert a string into an integer * * by Kyle Turley http://www.kturley.com */ #include <string> int StringToInt (std::string str) { int total = 0; int length = str.length(); // the length of the string int x = 1; // this is our multiplier, used to convert each digit into tens, units, etc for (int i = 1; i < str.length(); i++) x *= 10; // initialise x correctly for (int i = 0; i < length; i++) { // loop through the string // 48 is the base value (ASCII) // multiply it by x to get it into tens, units, etc total += (static_cast <int> (str[i]) - 48) * x; x /= 10; // divide x by 10, to reduce the units by one (thousands, then hundreds, etc) } return total; // return the value as an integer } <br /> /** EXAMPLE USAGE **/<br /> #include <iostream><br /> int main ()<br /> {<br /> std::string s = “12345”;<br /> int t = StringToInt(s) + 300;<br /> std::cout < < t; // should be 1534 (1234 + 300 = 1534)</p> <p> std::cin.get ();<br /> return EXIT_SUCCESS;<br /> }<br />