Atoi in C++

Atoi-in-C.jpg

Converting a C-string into an integer value in C++ is done by using the atoi() function. It is one of the simplest and most used functions for this task. Atoi is a built-in function of the standard C++ library, which is defined in the <cstdlib> header. In this article, we will discuss what the atoi() function in C++ is, its working with examples, how to create a custom atoi function in C++, advantages, disadvantages, and other alternatives to atoi in C++.

Table of Contents:

What is the atoi() Function in C++?

What is the atoi() Function in C++?

The atoi() function in C++ is a function that is used to convert a C-style string into an integer. It is a function of the standard C++ library and is defined in the <cstdlib> header. Atoi stands for “ASCII to Integer”. The function reads from left to right and recognizes an optional ‘+’ or ‘-‘ sign before converting numeric characters into an integer while ignoring any leading white spaces. Also, if the string contains non-numeric characters after the number, then these characters are ignored. 

Syntax of atoi in C++:

int atoi(const char* str);

Here, 

  • int: It is the return type of the converted integer value. 
  • const char* str: It is the parameter, basically a pointer to the C-style string.
  • str: It is the string that is to be converted into an integer value. 

Example:

Cpp

Output:

atoi() Function example

The code shows how the atoi() function is used to convert the string “123” into an integer value, and then prints it to the console. This example explains how a common method of C++ type conversion works.

How atoi() Works in C++

Below are a few steps that show how atoi works in C++:

Step 1: The atoi() function ignores whitespace.

It skips any space or whitespace characters that are present at the start of the string.

Step 2: Now, it checks for the sign.

It checks whether an optional ‘+’ or ‘-‘ sign is present to determine if the number is positive or negative.

Step 3: Then, convert digits.

After checking the sign, the atoi() function converts the consecutive numeric characters into an integer value from the first digit.

Step 4: Stops at a character.

The process of conversion stops as soon as it encounters a character that is not a digit. 

Step 5: Finally, it returns an integer value.

The atoi function finally returns an integer value as a result of the conversion with the appropriate sign. 

Note: If the string does not start with a valid number, then the atoi() function in C++ returns 0 and does not give an error. Also, this is a crucial point to understand how atoi works in C++.

How to Write Your Own atoi() Function in C++ (Step-by-Step)

To write our own atoi() function in C++, follow these steps.

1. You must start by skipping the leading whitespace characters in the string to reach the number part of the string.

while (str[i] == ' ') {
i++;
}

2. Now, you should check for the optional ‘+’ or ‘-‘ sign.

if (str[i] == '+' || str[i] == '-') {
sign = (str[i] == '-') ? -1 : 1;
i++;
}

3. Then, loop through each digit, convert it to an integer value, multiply the previous result by 10, and add the new digit to get the result.

while (str[i] >= '0' && str[i] <= '9') {
digit = str[i] - '0';
result = result * 10 + digit;
i++;
}

4. You must stop the loop when a character is found.

while (str[i] >= '0' && str[i] <= '9') {
// conversion logic
i++;
}

5. Now, finally, apply the sign to the result, and the result is an integer value.

return result * sign;

Example:

Cpp

Output:

Write Your Own atoi() Function in C++

The code shows how a custom myAtoi() function is created that converts the string “-456abc” into an integer value, by skipping whitespaces, signs, and non-digit characters. Then, the main function prints the converted number “-456” to the console. This example explains how to create a custom atoi function in C++.

Examples of atoi() in C++

Here are a few examples of atoi() in C++ that will help you to understand the C++ string to int conversion:

Example 1: String with Leading Spaces

Cpp

Output:

Example 1- String with Leading Spaces

The code shows how to use atoi() in C++ to convert the string ”   628″ with the leading spaces into the integer value 628, because it automatically skips the whitespace before converting, and then prints it to the console. This example shows the flexibility of C++ string to int conversion with atoi().

Example 2: String with Letters After Number

Cpp

Output:

Example 2: String with Letters After Number

The code shows how to convert string to int using atoi in C++, where the string is “321nir”, which has letters after the numbers, into an integer value, as the process stops as soon as the first non-digit character arrives. Then, the final converted number is printed to the console.

Get 100% Hike!

Master Most in Demand Skills Now!

Example 3: Negative Number

Cpp

Output:

Example 3 - Negative Number

The code shows how to use atoi() in C++ to convert the string “-789” into an integer value -789 with handling the negative sign correctly, and then prints the result to the console.

Example 4: Invalid String (No Digits)

Cpp

Output:

Example 4: Invalid String (No Digits)

The code shows how the atoi() function is used to convert the non-numeric string “abc”, which returns 0 since no valid digits are found at the start of the string.

Example 5: String Starting with Zero

Cpp

Output:

Example 5: String Starting with Zero

The code shows how the atoi() is used to convert the string “007000”, which has zeroes at the start, into an integer value, as it removes the leading zeroes automatically before printing the result 7000 to the console.

When Should You Use atoi() in C++?

  • You can use atoi() when you have a C-style string (const char*) which represents a number, and there is a need for C++ type conversion into an int.
  • When error handling is not a priority, then you can use atoi() because it returns 0 both for the string “0” and for invalid strings like “abc”, but it can convert a string into an int quickly.
  • You can use atoi in C++ to write small and simple code when performance is important and accuracy is not a concern.
  • You can use atoi() in code when you have to maintain legacy C code or write in a C/C++ hybrid environment.

Benefits of Using atoi() in C++ Programs

  • The atoi() function in C++ is very simple and easy to use.
  • It has a very straightforward syntax.
  • Atoi has a fast performance in converting a string into an integer with minimal overhead.
  • It is a standard library function, so no external dependencies are required.

Limitations of atoi() and Why You Should Avoid It

  • It has no error handling measures; thus, if the input is invalid or empty, atoi in C++ returns 0, and creates confusion that it is due to an actual 0 or an error.
  • The atoi() function in C++ has no exception support, as it does not throw exceptions on invalid input or overflow.
  • It is not suitable for large strings that exceed int limits.
  • The atoi() function is an older version of the C-style function, and modern C++ always prefers safer alternatives such as std::stoi().

Best Alternatives to atoi() in Modern C++

Below are a few other methods that are used to convert a string into an integer in C++. These also represent different forms of C++ type conversion.

1. std::stoi()

The std::stoi() is a safe and modern function from the C++11 standard library. It is used for C++ string to int conversion and throws exceptions if the input is invalid. This is a common C++ string to int conversion method.

Example:

Cpp

Output:

std::stoi()

The code shows how the std::stoi() function is used to convert the string “1122” into an integer value 1122, and then the result is printed to the console.

2. std::stringstream

The std::stringstream in C++ is part of the <sstream> header. It reads data from a string in the form of a stream. It is used to convert the strings into various data types. It is slightly slower and more verbose than the std::stoi().

Example:

Cpp

Output:

 std::stringstream

The code shows how the std::sstream() function is used to convert the string “345” into an integer value 345, and then the result is printed to the console.

3. std::from_chars()

The std::from_chars() is a fast, but low-overhead function that is used for converting characters to numbers. It throws exceptions and is suitable for complex codes.

Example:

Cpp

Output:

std::from_chars()

The code shows how the std::from_chars() function is used to convert the string “10205” into an integer value 10205, and then the result is printed to the console.

atoi() vs std::stoi() vs stringstream: Which One to Use in C++?

Aspect atoi() std::stoi() std::stringstream
Introduced in C (part of <cstdlib>) C++11 (part of <string>) C++98 (part of <sstream>)
Input type const char* (C-style string) std::string or const char* std::string (or anything streamable)
Error handling None, it returns 0 on failure Throws std::invalid_argument or std::out_of_range You can check .fail() or .eof() to detect errors
Performance Very fast Fast (but a bit slower than atoi()) Generally slower (more overhead)
Type safety Low High, strongly typed High, flexible for various types
Exception support No Yes (throws on errors) No exceptions, but manual error checking
Locale awareness No No Yes, it can be locale-aware
Usage complexity Easiest but unsafe Simple and safe Verbose but flexible
Recommended for Legacy C code, simple, quick conversions without error concern Modern C++ code where error detection matters Converting multiple types or parsing complex data

Conclusion

The atoi() function in C++ is a fast and easy method to convert a string into an integer value. It has some advantages, but it also lacks error handling and modern safety features. Thus, for complex applications, you must use better alternatives than the atoi() function in C++. So, by understanding the atoi in C++ with its working, examples, advantages, and disadvantages, you can use it in a better manner to convert a string into an integer value.

FAQs on Atoi in C++

Q1. What does atoi in C++ stand for?

atoi stands for “ASCII to Integer” and is used to convert a C-style string to an integer value.

Q2. What does atoi() do in C++?

atoi in C++ converts a C-style string (const char*) representing an integer into an int, and returns 0 if the input is invalid.

Q3. How is atoi() different from stoi() in C++?

atoi() converts without checking for errors, while std::stoi() checks for errors and throws exceptions if something goes wrong.

Q4. Which header file is required for atoi in C++?

You need to include for using the atoi() function in C++.

Q5. What are the best alternatives to atoi in C++?

The safer and better alternatives to the atoi() function in C++ are std::stoi(), std::stringstream, and std::from_chars().

Q6. Does atoi() handle negative numbers correctly?

Yes, atoi() can recognize and convert strings with a leading “-” sign into negative integers.

Q7. What happens if the input to atoi() is invalid?

If the string doesn’t start with a valid number, atoi() returns 0 without any error message.

Q8. Why does atoi return 0 sometimes even when the input is invalid?

Because atoi() cannot distinguish between the string “0” and invalid strings, it returns 0 in both cases without error reporting.

Q9. Can I use atoi() with std::string in C++?

Not directly, you must call .c_str() on the std::string (e.g., atoi(myString.c_str())) to convert it.

Q10. How to use atoi() in C++?

To use atoi in C++, call the atoi() function with a C-style string to convert it to an integer.

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