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
.
Here are examples. Notice what happens when not-integer characters are passed as the input:
And now for the inverse function. Here's how to convert from int
to string
.