This little piece of code can convert a string of decimal characters into an integer value.  If you seek to convert a string into a double, see this post.

/*
 * A function to convert a string into an integer
 */

#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
    }

    return total; // return the value as an integer
}

/** EXAMPLE USAGE **/
#include <iostream>
int main ()
{
    int t = StringToInt("1234") + 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.