Convert a String to an int in C++

C++ string to int conversion, lists vs constructors, which one is better, or should I say safe or error-free, is a question that lots of C++ beginners and even experienced developers also question. So, whether you are using stoi() calls, stringstream, or even manual loops, there are a few ways to do it. Not all are equal! In this guide, we will discover all the best ways to convert a string to an int in C++, along with real examples, pros, cons, and clear code explanations to leave no room for confusion.

Table of Contents:

What are Data Types in C++? 

C++ provides several fundamental data types to specify the size and type of information that a variable can store. The most common and efficient data types are int and string. Int stores whole numbers except the decimals, and string is used to store the text data. However, string is a part of the C++ standard library, so it must be included as #include<string>.

Data Type Description Example
int Integer numbers
int a = 10;
float Single-precision decimal numbers
float b = 5.5;
double Double-precision decimal numbers
double c = 9.99;
char Single character
char d = 'A';
bool Boolean value (true/false)
bool e = true;
void No value (used for functions)
void func();

How to Declare and Initialize an int in C++

The int data type stores whole numbers, i.e., ( aka integer type), positive and negative numbers without decimals.

Example:

Cpp

Output: 

How to Declare and Initialize an int in C++

The above C++ program declares an integer variable age with a value of 25, and you can use cout in C++ to print this value.

How to Declare and Initialize a String in C++

String is used to store text and it is initialized by using the std::string class. To declare the string, you have to use the <string> header in your program. 

Example: 

Cpp

Output: 

How to Declare and Initialize a String in C++

Here, the above code uses the <string> header to declare the string. The string greeting initializes the “Hello, C++!” text. By using the cout, the initialized text is displayed on your console. 

How to Convert a String to an Integer.

In C++, converting from a string to an integer is a very basic thing. These methodologies are useful, especially when you are reading integer elements from user input, files, or different text-based information sources. We can convert the strings to integers in multiple ways. Both of these methods serve different use cases as performance, input reliability, etc.

1. Using stoi() Function

In C++, the stoi() function provides a simple and efficient way to convert a string to an int datatype.  It is declared by using the header <string> and belongs to the std namespace.

Example:

Cpp

Output: 

1. Using stoi() Function

In the above code, after initializing the <string> header, the string declaration follows. The string str = “123” declares the number(123) as a string by using double quotes. Now, using stoi, it converts the string into a number; using cout, the number is displayed on your console. 

2. Using atoi() Function

The atoi() function is a C-style function that converts a C-string to an integer. To declare this function in C++, we have to use the <cstdlib> header in our program. 

Example: 

Cpp

Output: 

2. Using atoi() Function

In the above program, we use atoi() to change the C-style string “456” to an integer. The result is printed with cout. 

Difference between stoi() and atoi() 

Feature atoi stoi
Full Name ASCII to Integer String to Integer
Header <cstdlib> <string>
Namespace Global (C-style) std:: (C++-style)
Input Type C-style string (char*) std::string
Return Type int int
Error Handling No built-in error handling Throws exceptions on invalid input
Introduced In C C++11
Example
#include <cstdlib>
#include <iostream>
using namespace std;

int main() {
    const char* str = "123";
    int num = atoi(str);
    cout << num;
    return 0;
}
// Output: 123
                    
#include <string>
#include <iostream>
using namespace std;

int main() {
    string str = "123";
    int num = stoi(str);
    cout << num;
    return 0;
}
// Output: 123
                    

3. Using stringstream

The stringstream class is declared in the header file as <sstream>, which is part of the C++ standard library. Stringstream guarantees a robust and effective approach to transforming the string into any separate data type. It acts as an alternative to atoi() and is extremely helpful when dealing with formatted input.

Syntax: 
std::stringstream ss;
ss << string_value;
ss >> int_variable;
Example: 

Cpp

Output: 

3. Using stringstream

In the above program, we use the header to declare the string stream. Now in this program, the string”789”, which got stored in the variable str, is type casted to an integer. The stringstream object ss is created and initialized with str. An integer value is retrieved from the stream into the variable num using the operator >>. Finally, the converted number is printed using the cout.

4. Using sscanf() Function

The sscanf() is a member of the C standard library, which is declared for taking data formatted like a C-string. sscanf() works like printf(); however, instead of reading from the user, it reads from a string.

Example: 

Cpp

Output: 

4. Using sscanf() Function

Here, the above code shows how to convert a C-style string “321” to an integer using the sscanf() method provided by the standard library in C. It saves the string in the char array str. ” num = sscanf( str, “%d” ); Then the program prints the converted number. cout will show the output on the console.

5. Using a For Loop (Manual Method)

We can convert the string into only digits by using a manual method for-loop, which generates a digit in a step-by-step approach.  This method is very efficient for learning how the conversion happens between the data types. 

Example: 

Cpp

Output: 

5. Using a For Loop (Manual Method)

The program demonstrates how to convert the string “234” into an integer using a loop manually. You start with num = 0, then iterate through the digits in the string, converting it to an int by subtracting a character (‘0’) from the string. It computes the value using num = num * 10 + (c – ‘0’). After the loop, it prints the last number, 234. This illustrates how the internal operation of a string to an integer conversion works.

6. Using strtol() Function

Unlike atoi(), this strtlol() function is more robust and efficient in error checking. This function is used to detect invalid input or out-of-range values, which makes it safer and more reliable for use in real-world applications. 

Example: 

Cpp

Output: 

6. Using strtol() Function

The following program converts the string “987” to an int using strtol(). At first, it takes the string, a pointer end from where to know where the conversion stops, and the base (10). This result is also stored in num and printed. Unlike atoi(), the strtol() function allows some very minimal error checking via the end pointer.

Get 100% Hike!

Master Most in Demand Skills Now!

Conclusion

There are several ways to convert a string to an int in modern C++ code, The stoi() function is a simple and safe approach. Functions like atoi() and sscanf() are legacy methods and don’t handle errors gracefully. For production applications, you might use strtol() or stringstream. It helps you understand all the methods better and ultimately write better and more reliable code.

Convert a String to an int in C++ – FAQs

1. What is the safest way to convert a string to an int in C++?

In C++, std::stoi() ensures safe conversion with error handling.

2. Can I convert a string to an int without using libraries?

Yes, we can convert the string to an int by using the manual conversion for-loop.

3. What's the difference between atoi() and stoi()?

In C++, both are used for converting the string to an int, but the atoi() function doesn’t check for errors, and stoi() throws an exception for invalid input. 

4. How do I convert a std::string using atoi()?

In C++, .c_str() method like atoi(str.c_str()) for conversion.

5. Which method is best for handling invalid input?

Both the stoi() and stringstream methods are preferred for handling invalid input and error checking.  

About the Author

Technical Research Analyst - Full Stack Development

Kislay is a Technical Research Analyst and Full Stack Developer with expertise in crafting Mobile applications from inception to deployment. Proficient in Android development, IOS development, HTML, CSS, JavaScript, React, Angular, MySQL, and MongoDB, he’s committed to enhancing user experiences through intuitive websites and advanced mobile applications.

Full Stack Developer Course Banner