CodeBlanks Logo Icon CodeBlanks

stoi and stod

Learn string-to-number conversion with stoi and stod.

stoi: string to integer

Sometimes you need to convert an entire string into a single number. The stoi function turns a string into an integer; it skips leading whitespace and stops at the first non-digit character.

string s = "42";
int n = stoi(s);  // n = 42

If the string does not contain a valid number, std::invalid_argument is thrown. For this reason it is often wise to wrap the stoi call in a try block; we will cover exceptions in more detail later.

stod: string to double

For decimal numbers, the stod function is used. It works the same way as stoi; only the return type is double, and the decimal part after the dot is supported.

string s = "3.14";
double pi = stod(s);  // pi = 3.14

stod also throws std::invalid_argument on invalid input. Scientific notation like "1.5e3" is also supported, so you can safely fold user-supplied text into numeric calculations.

Practice Convert two numbers from strings and multiply

Define the string variables string a = "6"; and string b = "7.5";. Convert a to an integer with stoi and b to a double with stod. Print the product of the two numbers with cout.

Starter code

main.cpp
#include <iostream>
#include <string>
using namespace std;

int main() {
    string a = "6";
    string b = "7.5";
    // convert to numbers with stoi and stod, print their product
    return 0;
}

Sample solution

main.cpp
#include <iostream>
#include <string>
using namespace std;

int main() {
    string a = "6";
    string b = "7.5";
    int ia = stoi(a);
    double db = stod(b);
    cout << ia * db << endl;
    return 0;
}

Expected output

45

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does stoi("42") return?

  • "42"
  • 42 Correct answer
  • 42.0
  • '4'

Explanation: stoi returns an int value; it is 42.

2 Fill in the blank: stod call

Question
string s = "9.81";
double g = ____(s);
Answer
string s = "9.81";
double g = stod(s);

Explanation: stod converts decimal numbers.

3 Match each function with its return type

Term Meaning
stoi int
stod double
to_string string

All lessons in Beginner