There is strtol which is better IMO. Also I have taken a liking in strtonum, so use it if you have it (but remember it's not portable):

long long
     strtonum(const char *nptr, long long minval, long long maxval,
     const char **errstr);

You might also be interested in strtoumax and strtoimax which are standard functions in C99. For example you could say:

uintmax_t num = strtoumax(s, NULL, 10);
if (num == UINTMAX_MAX && errno == ERANGE)
    /* Could not convert. */

Anyway, stay away from atoi:

The call atoi(str) shall be equivalent to:

(int) strtol(str, (char **)NULL, 10)

except that the handling of errors may differ. If the value cannot be represented, the behavior is undefined.

Answer from cnicutar on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › c language › convert-string-to-int-in-c
Convert String to int in C - GeeksforGeeks
July 23, 2025 - The atoi() function in C takes a character array or string literal as an argument and returns corresponding value as integer. It is defined in the <stdlib.h> header file. If you observe the name atoi() a little closer, you will find out that ...
Top answer
1 of 14
253

There is strtol which is better IMO. Also I have taken a liking in strtonum, so use it if you have it (but remember it's not portable):

long long
     strtonum(const char *nptr, long long minval, long long maxval,
     const char **errstr);

You might also be interested in strtoumax and strtoimax which are standard functions in C99. For example you could say:

uintmax_t num = strtoumax(s, NULL, 10);
if (num == UINTMAX_MAX && errno == ERANGE)
    /* Could not convert. */

Anyway, stay away from atoi:

The call atoi(str) shall be equivalent to:

(int) strtol(str, (char **)NULL, 10)

except that the handling of errors may differ. If the value cannot be represented, the behavior is undefined.

2 of 14
46

Robust C89 strtol-based solution

With:

  • no undefined behavior (as could be had with the atoi family)
  • a stricter definition of integer than strtol (e.g. no leading whitespace nor trailing trash chars)
  • classification of the error case (e.g. to give useful error messages to users)
  • a "testsuite"
#include <assert.h>
#include <ctype.h>
#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>

typedef enum {
    STR2INT_SUCCESS,
    STR2INT_OVERFLOW,
    STR2INT_UNDERFLOW,
    STR2INT_INCONVERTIBLE
} str2int_errno;

/* Convert string s to int out.
 *
 * @param[out] out The converted int. Cannot be NULL.
 *
 * @param[in] s Input string to be converted.
 *
 *     The format is the same as strtol,
 *     except that the following are inconvertible:
 *
 *     - empty string
 *     - leading whitespace
 *     - any trailing characters that are not part of the number
 *
 *     Cannot be NULL.
 *
 * @param[in] base Base to interpret string in. Same range as strtol (2 to 36).
 *
 * @return Indicates if the operation succeeded, or why it failed.
 */
str2int_errno str2int(int *out, char *s, int base) {
    char *end;
    if (s[0] == '\0' || isspace((unsigned char) s[0]))
        return STR2INT_INCONVERTIBLE;
    errno = 0;
    long l = strtol(s, &end, base);
    /* Both checks are needed because INT_MAX == LONG_MAX is possible. */
    if (l > INT_MAX || (errno == ERANGE && l == LONG_MAX))
        return STR2INT_OVERFLOW;
    if (l < INT_MIN || (errno == ERANGE && l == LONG_MIN))
        return STR2INT_UNDERFLOW;
    if (*end != '\0')
        return STR2INT_INCONVERTIBLE;
    *out = l;
    return STR2INT_SUCCESS;
}

int main(void) {
    int i;
    /* Lazy to calculate this size properly. */
    char s[256];

    /* Simple case. */
    assert(str2int(&i, "11", 10) == STR2INT_SUCCESS);
    assert(i == 11);

    /* Negative number . */
    assert(str2int(&i, "-11", 10) == STR2INT_SUCCESS);
    assert(i == -11);

    /* Different base. */
    assert(str2int(&i, "11", 16) == STR2INT_SUCCESS);
    assert(i == 17);

    /* 0 */
    assert(str2int(&i, "0", 10) == STR2INT_SUCCESS);
    assert(i == 0);

    /* INT_MAX. */
    sprintf(s, "%d", INT_MAX);
    assert(str2int(&i, s, 10) == STR2INT_SUCCESS);
    assert(i == INT_MAX);

    /* INT_MIN. */
    sprintf(s, "%d", INT_MIN);
    assert(str2int(&i, s, 10) == STR2INT_SUCCESS);
    assert(i == INT_MIN);

    /* Leading and trailing space. */
    assert(str2int(&i, " 1", 10) == STR2INT_INCONVERTIBLE);
    assert(str2int(&i, "1 ", 10) == STR2INT_INCONVERTIBLE);

    /* Trash characters. */
    assert(str2int(&i, "a10", 10) == STR2INT_INCONVERTIBLE);
    assert(str2int(&i, "10a", 10) == STR2INT_INCONVERTIBLE);

    /* int overflow.
     *
     * `if` needed to avoid undefined behaviour
     * on `INT_MAX + 1` if INT_MAX == LONG_MAX.
     */
    if (INT_MAX < LONG_MAX) {
        sprintf(s, "%ld", (long int)INT_MAX + 1L);
        assert(str2int(&i, s, 10) == STR2INT_OVERFLOW);
    }

    /* int underflow */
    if (LONG_MIN < INT_MIN) {
        sprintf(s, "%ld", (long int)INT_MIN - 1L);
        assert(str2int(&i, s, 10) == STR2INT_UNDERFLOW);
    }

    /* long overflow */
    sprintf(s, "%ld0", LONG_MAX);
    assert(str2int(&i, s, 10) == STR2INT_OVERFLOW);

    /* long underflow */
    sprintf(s, "%ld0", LONG_MIN);
    assert(str2int(&i, s, 10) == STR2INT_UNDERFLOW);

    return EXIT_SUCCESS;
}

GitHub upstream.

Based on: https://stackoverflow.com/a/6154614/895245

Discussions

Beginner needing help, converting string to integer.
What you want is stoi but since you can't use it, you will have to manually parse the string. The way it goes is, we inspect each individual character in string and if it is between '0' (0x30) and '9' (0x39), we subtract '0' from this value. Say the character is '4' (0x34) so the arithmatic will be 0x34 - 0x30 = 4 We do this for every letter and we have integer value. So something like define variable num start for loop from 0 till str.size() if character is between '0' and '9', subtract '0' and save in val num = num*10 + val end for loop More on reddit.com
🌐 r/Cplusplus
17
4
November 9, 2022
Converting char/string to int?
Do you notice any warnings about your code when you compile it? Specifically these lines: int toInt1 = string1; int toInt2 = string2; For a quick solution, look up the function, atoi. You can use it to convert your strings to ints. In general, the function, strtol, is probably what you want to learn about for converting strings to integers. You might also find sscanf useful. Also, read up on printf. The %s is only for strings. Use %d for ints. More on reddit.com
🌐 r/C_Programming
7
0
June 19, 2018
c++ - How can I convert a std::string to int? - Stack Overflow
I want to convert a string to an int and I don't mean ASCII codes. For a quick run-down, we are passed in an equation as a string. We are to break it down, format it correctly and solve the linear More on stackoverflow.com
🌐 stackoverflow.com
How can I convert an int to a string in C? - Stack Overflow
How do you convert an int (integer) to a string? I'm trying to make a function that converts the data of a struct into a string to save it in a file. More on stackoverflow.com
🌐 stackoverflow.com
People also ask

Why do we need to convert string to int in C?
We need to convert string to int in C because user inputs or file data are usually strings, but numeric calculations require integers.
🌐
wscubetech.com
wscubetech.com › resources › c-programming › programs › string-to-int
How to Convert String to Int in C? 5 Ways With Code
What is the easiest way to convert string to int in C?
The easiest way to convert string to int in C is by using the built-in atoi() function from the library.
🌐
wscubetech.com
wscubetech.com › resources › c-programming › programs › string-to-int
How to Convert String to Int in C? 5 Ways With Code
How does manual string to int conversion work in C?
Each character of the string is processed one by one, converted into its numeric digit, and combined to form the final integer value.
🌐
wscubetech.com
wscubetech.com › resources › c-programming › programs › string-to-int
How to Convert String to Int in C? 5 Ways With Code
🌐
Udemy
blog.udemy.com › home › it & development › software development › c string to int: simple ways to convert to numeric values
C String to Int: Simple Ways to Convert to Numeric Values - Udemy Blog
April 14, 2026 - Initially, in this program, we include stdio.h and string.h from the C standard library. This lets us use the functions that are part of these header files. The C programming language doesn’t automatically include functions like these. You must import them into your software to use them.
🌐
WsCube Tech
wscubetech.com › resources › c-programming › programs › string-to-int
How to Convert String to Int in C? 5 Ways With Code
September 17, 2026 - Learn five easy ways to convert a string to an int in C using atoi(), strtol(), sscanf(), and manual conversion. Includes code examples!
Find elsewhere
🌐
Scaler
scaler.com › home › topics › convert string to int in c++
Convert String to Int in C++ - Scaler Topics
February 5, 2026 - If the starting character is a non-integer value, the stoi() function terminates, giving an error as shown in the output. ... A hands on AI engineering program covering Machine Learning, Generative AI, and LLMs - designed for working professionals & delivered by IIT Roorkee in collaboration ...
🌐
ByteHide
bytehide.com › blog › turning a string into an int in c#: full guide
Turning a String into an Int in C#: Full Guide - ByteHide
March 27, 2025 - A ‘String’ usually contains words and phrases (like “Hello World!”), while ‘Int’ stands for integer, which is a number without a fractional part (like 42.00). So when we say “convert string to int,” we’re talking about taking a number that’s been formatted as a string (like “42”) and converting it back into an integer (like 42).
🌐
Codecademy
codecademy.com › article › how-to-convert-a-string-to-an-integer-in-c
How to Convert a String to an Integer in C++ | Codecademy
It involves explicitly handling each character and incrementally building the final integer. ... This example demonstrates how to manually convert the string “456” to an integer using a for loop:
🌐
Reddit
reddit.com › r/c_programming › converting char/string to int?
r/C_Programming on Reddit: Converting char/string to int?
June 19, 2018 -

Hey all. I am trying to convert strings/chars to ints for a number guessing game. I have created this simple program that is supposed to start out with two character arrays and then convert them into an int, then add the two. It doesn't seem to be working. I get no output. Now I am pretty new to C. I am used to JavaScript where you can just sling data types anywhere you want, so this concept in C is giving me some trouble. Any help would be great! Thanks!

Code:

#include <stdio.h>

#include <stdlib.h>

#include <math.h>

int main(){

char string1[5] = "1234";

char string2[5] = "1000";

printf("String one says: %s \n", string1);

printf("String two says: %s \n \n", string2);

int toInt1 = string1;

int toInt2 = string2;

int add_ints = toInt1 + toInt2;

printf("String one should now be an int: %s \n", toInt1);

printf("String two should now be an int: %s \n", toInt2);

printf("So adding them together should produce: %s", add_ints);

}

🌐
TutorialsPoint
tutorialspoint.com › article › How-to-convert-a-string-to-a-integer-in-C
How to convert a string to a integer in C
int atoi(const char *str); long strtol(const char *str, char **endptr, int base); int sscanf(const char *str, const char *format, ...); The atoi() function converts a string to an integer.
🌐
FavTutor
favtutor.com › blogs › string-to-int-cpp
String to Int in C++ (5 Ways) | FavTutor
July 21, 2026 - In C++, you convert a string to an int with the std::stoi() function from the <string> header: stoi("42") returns the int 42.
🌐
GitHub
gist.github.com › shamiul94 › 02d4957f410b138ef8aca6b7602d12b6
String to Integer Conversion.c · GitHub
Save shamiul94/02d4957f410b138ef8aca6b7602d12b6 to your computer and use it in GitHub Desktop. ... This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Top answer
1 of 2
1186

In C++11 there are some nice new convert functions from std::string to a number type.

So instead of

atoi( str.c_str() )

you can use

std::stoi( str )

where str is your number as std::string.

There are version for all flavours of numbers: long stol(string), float stof(string), double stod(string),... see http://en.cppreference.com/w/cpp/string/basic_string/stol

2 of 2
119

The possible options are described below:

1. sscanf()

    #include <cstdio>
    #include <string>

        int i;
        float f;
        double d;
        std::string str;

        // string -> integer
        if(sscanf(str.c_str(), "%d", &i) != 1)
            // error management

        // string -> float
        if(sscanf(str.c_str(), "%f", &f) != 1)
            // error management
    
        // string -> double 
        if(sscanf(str.c_str(), "%lf", &d) != 1)
            // error management

This is an error (also shown by cppcheck) because "scanf without field width limits can crash with huge input data on some versions of libc" (see here, and here).

2. std::sto*()

    #include <iostream>
    #include <string>

        int i;
        float f;
        double d;
        std::string str;

        try {
            // string -> integer
            int i = std::stoi(str);

            // string -> float
            float f = std::stof(str);

            // string -> double 
            double d = std::stod(str);
        } catch (...) {
            // error management
        }   

This solution is short and elegant, but it is available only on C++11 compliant compilers.

3. sstreams

    #include <string>
    #include <sstream>

        int i;
        float f;
        double d;
        std::string str;

        // string -> integer
        std::istringstream ( str ) >> i;

        // string -> float
        std::istringstream ( str ) >> f;

        // string -> double 
        std::istringstream ( str ) >> d;

        // error management ??

However, with this solution is hard to distinguish between bad input (see here).

4. Boost's lexical_cast

    #include <boost/lexical_cast.hpp>
    #include <string>

        std::string str;

        try {
            int i = boost::lexical_cast<int>( str.c_str());
            float f = boost::lexical_cast<int>( str.c_str());
            double d = boost::lexical_cast<int>( str.c_str());
            } catch( boost::bad_lexical_cast const& ) {
                // Error management
        }

However, this is just a wrapper of sstream, and the documentation suggests to use sstream for better error management (see here).

5. strto*()

This solution is very long, due to error management, and it is described here. Since no function returns a plain int, a conversion is needed in case of integer (see here for how this conversion can be achieved).

6. Qt

    #include <QString>
    #include <string>

        bool ok;
        std::string;

        int i = QString::fromStdString(str).toInt(&ok);
        if (!ok)
            // Error management
    
        float f = QString::fromStdString(str).toFloat(&ok);
        if (!ok)
            // Error management 

        double d = QString::fromStdString(str).toDouble(&ok);
        if (!ok)
    // Error management     
    

Conclusions

Summing up, the best solution is C++11 std::stoi() or, as a second option, the use of Qt libraries. All other solutions are discouraged or buggy.

🌐
W3Schools
w3schools.com › c › c_type_conversion.php
C Data Type Conversion
Convert a value from one C data type to another with implicit and explicit type conversion.
🌐
Microsoft Learn
learn.microsoft.com › en-us › dotnet › csharp › programming-guide › types › how-to-convert-a-string-to-a-number
How to convert a string to a number - C# | Microsoft Learn
The following example calls the Convert.ToInt32(String) method to convert an input string to an int. The example catches the two most common exceptions thrown by this method: FormatException and OverflowException.
🌐
Jonathan Cook
cs.nmsu.edu › ~jcook › posts › cpp-string-conversions
C/C++: Converting Strings to Numbers • Jonathan Cook
January 25, 2023 - The names are meaningful even if they are a little cryptic. atoi is short for “alpha-to-integer”, and converts a string to an integer. atol converts to a long integer, and atof converts to a floating point number (double). The “a” functions aren’t very flexible and have no way of communicating an error (such as maybe the string doesn’t contain a number anyways), so the “str” functions are better.
🌐
GeeksforGeeks
geeksforgeeks.org › c language › how-to-convert-an-integer-to-a-string-in-c
How to Convert an Integer to a String in C? - GeeksforGeeks
July 23, 2025 - In C, integers can be represented as strings with each digit represented by corresponding numeric character. In this article, we will learn how to convert integers into the string