What’s New ?

The Top 10 favtutor Features You Might Have Overlooked

Read More
Computer Science

String to Int in C++ (5 Ways with Examples)

Jul 21, 2026 5 Minutes Read Why Trust Us Why you can trust this guide. Written by working engineers and reviewed by our editorial team under a strict editorial policy for accuracy, clarity and zero bias. Anubhav Agarwal By Anubhav Agarwal Anubhav Agarwal Anubhav Agarwal
I'm a research-oriented engaged in various technologies and a technical content writer. Being a coder myself, going through the documentation to provide optimized solutions as technical content is what I always look for.
Connect on LinkedIn →
String to Int in C++ (5 Ways with Examples)

In C++, you convert a string to an int with the std::stoi() function from the <string> header: stoi("42") returns the int 42. It handles leading whitespace, a sign, and stops at the first non-digit character.

C++ also converts strings to numbers with stringstream, atoi() for C-style strings, strtol(), and a manual digit loop. This lesson shows all five ways, how each one handles invalid input, and the same conversion in plain C.

How Do You Convert a String to an Int in C++?

Call std::stoi() with the string, and it returns the parsed int.

#include <iostream>
#include <string>
using namespace std;

int main() {
    string age_input = "27";

    int age = stoi(age_input);
    cout << age + 1;  // Output: 28
    return 0;
}

The arithmetic works because age is a real int after the call, not text.

Five ways to convert a string to an int in C++: stoi, stringstream, atoi, strtol, and a manual digit loop

5 Ways to Convert a String to an Int

1) The stoi() Function

stoi() parses an optional sign and digits, ignores leading whitespace, and stops at the first character that is not part of a number. An optional second argument reports where parsing stopped, and a third sets the base.

#include <iostream>
#include <string>
using namespace std;

int main() {
    cout << stoi("  -350") << "\n";      // Output: -350
    cout << stoi("42km") << "\n";        // Output: 42
    cout << stoi("ff", nullptr, 16);     // Output: 255
    return 0;
}
How stoi parses a string in C++: skip whitespace, read the sign and digits, stop at the first non-digit character

2) A stringstream

The stringstream class from <sstream> reads formatted values out of a string the same way cin reads input. It is useful when a string holds several numbers.

#include <iostream>
#include <sstream>
#include <string>
using namespace std;

int main() {
    stringstream reader("2026 7 21");
    int year, month, day;

    reader >> year >> month >> day;
    cout << year + month + day;  // Output: 2054
    return 0;
}

3) The atoi() Function

atoi() from <cstdlib> converts a C-style string (const char*). On a std::string, call c_str() first. It returns 0 for invalid input, with no way to tell that apart from a real "0".

#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;

int main() {
    string code = "8080";

    cout << atoi(code.c_str()) << "\n";  // Output: 8080
    cout << atoi("oops");                // Output: 0
    return 0;
}

4) The strtol() Function

strtol() from <cstdlib> converts to a long and sets an end pointer to the first unparsed character, so you can check how much of the string was a valid number without exceptions.

#include <iostream>
#include <cstdlib>
using namespace std;

int main() {
    const char* text = "1500ms";
    char* end;

    long value = strtol(text, &end, 10);
    cout << value << "\n";  // Output: 1500
    cout << end;            // Output: ms
    return 0;
}

5) A Manual Digit Loop (Without stoi)

Converting without stoi() is a common exercise: multiply the result by 10 and add each digit's value, using the fact that '7' - '0' equals 7.

#include <iostream>
#include <string>
using namespace std;

int main() {
    string digits = "934";
    int number = 0;

    for (char c : digits) {
        number = number * 10 + (c - '0');
    }
    cout << number + 1;  // Output: 935
    return 0;
}

How stoi() Handles Invalid Input

stoi() throws an std::invalid_argument exception when the string starts with no digits, and std::out_of_range when the number does not fit in an int. Wrap the call in a try/catch to handle user input safely.

#include <iostream>
#include <string>
#include <stdexcept>
using namespace std;

int main() {
    string user_input = "abc";

    try {
        int value = stoi(user_input);
        cout << value;
    } catch (const invalid_argument& e) {
        cout << "not a number";  // Output: not a number
    }
    return 0;
}

When to Use Each Method

MethodUse it when
stoi()A std::string holds one number; you want exceptions on bad input
stringstreamThe string holds several values to read in sequence
atoi()Legacy C-style strings where 0-on-failure is acceptable
strtol()You need error checking without exceptions, or the leftover text
Manual loopInterview practice, or custom parsing rules

Examples of Converting a String to an Int

1) Summing Numbers From Text Input

#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main() {
    vector<string> prices = {"250", "499", "120"};
    int total = 0;

    for (const string& p : prices) total += stoi(p);
    cout << total;  // Output: 869
    return 0;
}

2) Parsing a Version Number

#include <iostream>
#include <string>
using namespace std;

int main() {
    string version = "14.2";
    size_t dot = version.find('.');

    int major = stoi(version.substr(0, dot));
    int minor = stoi(version.substr(dot + 1));
    cout << major << " " << minor;  // Output: 14 2
    return 0;
}

3) Reading a Number and Its Unit

#include <iostream>
#include <string>
using namespace std;

int main() {
    string distance = "42km";
    size_t parsed;

    int value = stoi(distance, &parsed);
    cout << value << " " << distance.substr(parsed);  // Output: 42 km
    return 0;
}

Learn More About String to Int Conversion

String to Int in C

C has no stoi(). Use atoi() for quick conversions or strtol() when you need error detection, both from <stdlib.h>. The manual digit loop also works unchanged in C.

String to Long, Float, and Double

The same family covers other types: stol() and stoll() for long and long long, stof() and stod() for float and double. stod("3.14") returns the double 3.14.

Can You Cast a String to an Int?

No. (int)text and static_cast<int>(text) do not compile, because a string is an object, not a number in disguise. Conversion always goes through a parsing function.

Converting an Int Back to a String

The reverse direction uses std::to_string(): to_string(42) returns the string "42".

Key Takeaways for String to Int in C++

  • stoi() - the standard way; handles whitespace, signs, other bases, and stops at the first non-digit.
  • Errors - stoi() throws invalid_argument or out_of_range; atoi() silently returns 0.
  • strtol() - exception-free error checking through its end pointer.
  • stringstream - reads several numbers out of one string in sequence.
  • No casting - a cast from string to int does not compile; use a parsing function.

Parsed numbers usually end up in a container next. Read our lesson on initializing a vector in C++ for the ways to set one up.

Anubhav Agarwal
About the author

Anubhav Agarwal

I'm a research-oriented engaged in various technologies and a technical content writer. Being a coder myself, going through the documentation to provide optimized solutions as technical content is what I always look for. Connect on LinkedIn →