String to number in C++

Level 3128 keystrokes

stoi converts a string to an int and stod converts it to a double, so the values can be used in arithmetic. Prints 84 and 6.28.

C++ code

// Numbers stored as text cannot be used in arithmetic yet
1string s1 = "42";
2string s2 = "3.14";
// stoi (string to int) parses "42" into the int 42
3int num = stoi(s1);
// stod (string to double) parses "3.14"; both throw invalid_argument if the text is not a number
4double pi = stod(s2);
// Now arithmetic works: 42 * 2 = 84
5cout << num * 2 << endl;
// 3.14 * 2 = 6.28
6cout << pi * 2 << endl;

Output

84
6.28
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C++ code and how often they appear.

  • <× 8
  • ;× 6
  • "× 4
  • =× 4
  • (× 2
  • )× 2
  • *× 2
  • .× 1

More C++ examples at level 3

← C++ typing practice