/*
* A function to convert a string into an integer
* Author: Danny Battison
* Author: Kyle Turley http://www.kturley.com
*/
#include
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  (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
}

/** EXAMPLE USAGE **/
#include
int main ()
{
std::string s = "12345";
int t = StringToInt(s) + 300;
std::cout << t; // should be 1534 (1234 + 300 = 1534)

 std::cin.get ();
return EXIT_SUCCESS;
}

Leave a Reply

Your email address will not be published.