Joel Verhagen

a computer programming blog

Convert an Int to a String and Vice Versa in C++

Often times when you are making a command line program in C++ you need to take user input via cin. I always find myself needing to convert an int to a string or a string to an int. Traditionally in C, people use the atoi library. Well, if for whatever reason you want to avoid that, you can use streams to do the conversion.

This will convert a string to an int.

int stringToInt(string input)
    stringstream s(input);
    int i;
    s >> i;
    return i;

Here are examples. Notice what happens when not-integer characters are passed as the input:

stringToInt("1337")    // 1337
stringToInt("0.5")     // 0
stringToInt("-1.7")    // -1
stringToInt("-0.3")    // 0
stringToInt("bad")     // 0
stringToInt("a1004a")  // 0
stringToInt("a1004")   // 0
stringToInt("1004a")   // 1004
stringToInt("-100")    // -100
stringToInt("-100.3")  // -100
stringToInt("-100.7")  // -100
stringToInt("    -97") // -97

And now for the inverse function. Here's how to convert from int to string.

string intToString(int input)
    stringstream s;
    s << input;
    return s.str();