Skip to content
C++ Better Explained
Go back
How to Convert String to int in C++: stoi, atoi, and stringstream
Edit page

How to Convert String to int in C++

If you’ve ever read a number from user input or a file, you’ve run into this problem: the number comes in as a std::string, but you need an int to do math with it. C++ gives you three main ways to make that conversion — stoi, atoi, and stringstream — and each has its place.


stoi stands for “string to integer.” It’s part of the <string> header and is the cleanest option for converting a std::string to an int.

#include <iostream>
#include <string>

int main() {
    std::string s = "42";
    int n = std::stoi(s);
    std::cout << n + 1 << "\n"; // prints 43
    return 0;
}

stoi also handles leading whitespace and an optional sign:

std::string s = "  -17";
int n = std::stoi(s); // n = -17

Error handling with stoi

stoi throws exceptions on bad input, which lets you catch problems instead of silently getting wrong answers:

#include <iostream>
#include <string>
#include <stdexcept>

int main() {
    std::string s = "hello";
    try {
        int n = std::stoi(s);
        std::cout << n << "\n";
    } catch (const std::invalid_argument& e) {
        std::cout << "Not a valid number: " << e.what() << "\n";
    } catch (const std::out_of_range& e) {
        std::cout << "Number too large for int: " << e.what() << "\n";
    }
    return 0;
}

This prints: Not a valid number: stoi

stoi also has a second parameter that tells you how many characters were consumed, which is useful for parsing:

std::string s = "123abc";
size_t pos;
int n = std::stoi(s, &pos); // n = 123, pos = 3
If you're looking to go deeper with C++, the C++ Better Explained Ebook is perfect for you — whether you're a complete beginner or looking to solidify your understanding. Just $19.

Method 2: atoi (For C-Style Strings)

atoi is the older C-style function from <cstdlib>. It converts a const char* (not a std::string) to an int.

#include <iostream>
#include <cstdlib>

int main() {
    const char* s = "99";
    int n = atoi(s);
    std::cout << n << "\n"; // prints 99
    return 0;
}

To use atoi with a std::string, call .c_str() to get the underlying C-string:

#include <iostream>
#include <string>
#include <cstdlib>

int main() {
    std::string s = "99";
    int n = atoi(s.c_str());
    std::cout << n << "\n"; // prints 99
    return 0;
}

The big warning with atoi: if the string is not a valid number, it returns 0 — silently. There’s no exception, no error message. This makes bugs very hard to find:

int n = atoi("hello"); // n = 0, no error
int m = atoi("");      // m = 0, no error

Prefer stoi for new code. Use atoi only when working with C APIs that hand you char*.


Method 3: stringstream

std::stringstream from <sstream> treats a string like a stream you can read from. This approach works for converting any type, not just strings to ints.

#include <iostream>
#include <string>
#include <sstream>

int main() {
    std::string s = "55";
    std::istringstream ss(s);
    int n;
    ss >> n;
    std::cout << n << "\n"; // prints 55
    return 0;
}

You can also check whether the conversion succeeded:

std::string s = "abc";
std::istringstream ss(s);
int n;
if (ss >> n) {
    std::cout << "Converted: " << n << "\n";
} else {
    std::cout << "Conversion failed\n";
}

stringstream is more verbose than stoi, but it’s very flexible — you can chain multiple extractions from a single string, or convert to double, long, etc. with no extra syntax.


Which Method Should You Use?

MethodWorks withError handlingBest for
stoistd::stringThrows exceptionsMost cases in modern C++
atoiconst char*Returns 0 silentlyLegacy/C code
stringstreamstd::stringReturns false on failMultiple conversions, any type

For beginner programs, use stoi and wrap it in a try/catch when working with user input. It’s the safest and most readable option.


Complete Example: Safe User Input to int

Here’s a complete program that reads a number from the user, handles bad input, and keeps asking until it gets a valid integer:

#include <iostream>
#include <string>
#include <stdexcept>

int getInt(const std::string& prompt) {
    while (true) {
        std::cout << prompt;
        std::string line;
        std::getline(std::cin, line);
        try {
            size_t pos;
            int n = std::stoi(line, &pos);
            if (pos == line.size()) { // whole string was a number
                return n;
            }
            std::cout << "Please enter a whole number.\n";
        } catch (...) {
            std::cout << "Please enter a whole number.\n";
        }
    }
}

int main() {
    int age = getInt("Enter your age: ");
    std::cout << "In 10 years you'll be " << age + 10 << ".\n";
    return 0;
}

This is a pattern you’ll use constantly when writing interactive C++ programs.



Take Your C++ Further

If you’re looking to go deeper with C++, the C++ Better Explained Ebook is perfect for you — whether you’re a complete beginner or looking to solidify your understanding. Just $19.

👉 Get the C++ Better Explained Ebook — $19

📋

Free Download: The 10 Mistakes Every C++ Beginner Makes

A free 1-page checklist that shows the exact traps that slow down every C++ beginner — so you can avoid them from day one.

🔒 No spam. Unsubscribe anytime.


Edit page
Share this post on:

Previous Post
C++ std::set Tutorial: Sorted Unique Collections for Beginners
Next Post
C++ auto Keyword Explained: Type Deduction for Beginners