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 atoi() is, its working with examples, how to create your own atoi() function, advantages, disadvantages, and other alternatives to atoi() in C++.
Table of Contents:
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:
Output:
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.
How atoi() Works in C++
Below are a few steps that show how the atoi() function works.
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 returns 0 and does not give an error.
How to Write Your Own atoi() Function in C++
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:
Output:
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.
Examples Using atoi() in C++
Here are a few examples of converting a string into an integer value in C++.
Example 1: String with Leading Spaces
Output:
The code shows how the atoi() function is used 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.
Example 2: String with Letters After Number
Output:
The code shows how the atoi() function is used to convert the string “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
Output:
The code shows how the atoi() function is used 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)
Output:
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
Output:
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.
Advantages of atoi() in C++
- The atoi() function is very simple and easy to use.
- It has a very straightforward syntax.
- Atoi has fast performance in converting a string into an integer with minimal overhead.
- It is a standard library function, so no external dependencies are required.
Disadvantages of atoi() in C++
- It has no error handling measures; thus, if the input is invalid or empty, atoi() returns 0, and creates confusion that it is due ot an actual 0 or an error.
- The atoi() function 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().
Other Methods to Convert a String to an Integer in C++
Below are a few other methods that are used to convert a string into an integer in C++.
1. std::stoi()
The std::stoi() is a safe and modern function from the C++11 standard library. It is used to convert a string into an int and throws exceptions if the input is invalid.
Example:
Output:
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:
Output:
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:
Output:
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.
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 the complex applications, you must use better alternatives than the atoi() function in C++. So, by understanding the atoi() function 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() stand for?
Atoi stands for “ASCII to Integer” and is used to convert a C-style string to an integer value.
Q2. What happens if the input string is invalid?
If the string doesn’t start with a valid number, atoi() returns 0 without any error message.
Q3. Does atoi() handle negative numbers?
Yes, atoi() can recognize and convert strings with a leading “-” sign into negative integers.
Q4. Which header file is required for atoi()?
You need to include for using the atoi() function in C++.
Q5. What are the alternatives to atoi() in modern C++?
The safer and better alternatives to the atoi() function in C++ are std::stoi(), std::stringstream, and std::from_chars().