Return To CS 110 Home

Colour Theme   Font Size Options
 
   
   
   
String and Int Conversion

Converting Between Strings and Ints


Video Summary: https://youtu.be/Fi8q3RQR6m0


Sometimes, you will have input in one format, such as a string, but you will want to do math with it as if it were an int. However, using addition on strings concatenates them, which is probably not your intention. Additionally, you can't just typecast a string to an int.

There are mutliple ways you could convert between the two, but the easiest is to use the built in functions in c++:

  1. stoi (String TO Integer)
  2. to_string

The following code demonstrates how to use these functions:


Which produces the following output:

Adding two strings together: 123321
Adding the strings converted to ints: 444
Converting back to strings: 123321

Exercise

Create a program that has the user enter 3 numbers on one line as a string. Break the string into three integers and add the result. Convert the result back into a string and concatenate it with a larger output string.

  1. To read multiple words into one string, you will need to use getline(cin, stringName)
  2. To break the string up, you will need to use a combination of stringName.find(space) and string.substr(startpos, endpos)
  3. You will need to use stoi to convert each piece to an integer to add them
  4. You will need to use to_string on the result, then add it to an output string

When you are finished, your output might look like this:

Enter three numbers then hit enter
1 2 3
The result is 6

Solution