The conversion of a string to an integer (the library function is atoi) is a classic string processing problem in C, requiring consideration of various edge cases and exception handling. Below, we will implement a function similar to atoi and explain its implementation approach in detail.
Functional Requirement Analysis
- Ignore leading whitespace characters in the string
- Handle positive and negative signs (+, -)
- Convert numeric characters to their corresponding integer values
- Handle overflow situations that exceed the integer range
- Ignore non-numeric characters following the digits
- Handle empty strings or strings that are entirely non-numeric (return 0)
Main Processing Steps
1. Null Pointer Check
if (str == NULL) { return 0; }
First, check if the input string is NULL to avoid crashes in subsequent operations.2. Skip Whitespace Characters
while (isspace(str[i])) { i++; }
Use the isspace() function to identify whitespace characters (spaces, tabs , newlines , etc.) and skip them.3. Handle Positive and Negative Signs
if (str[i] == '+' || str[i] == '-') { sign = (str[i] == '-') ? -1 : 1; i++;}
Identify and record the sign, defaulting to positive.4. Number Conversion and Overflow Check
while (str[i] >= '0' && str[i] <= '9') { // Overflow check if (result > INT_MAX / 10 || (result == INT_MAX / 10 && str[i] - '0' > 7)) { return (sign == 1) ? INT_MAX : INT_MIN; } result = result * 10 + (str[i] - '0'); i++;}
- Only process numeric characters from
0-9 - Check for overflow before each calculation
- Convert character to number:
str[i] - '0'(using ASCII code properties)
5. Return Result
return result * sign;
Apply the sign and return the final result.
Overflow Check Principle
The range of integers is from<span>INT_MIN</span> (-2147483648) to<span>INT_MAX</span> (2147483647). When converting, if it may exceed this range:
- If the current result
<span>result > INT_MAX / 10</span>, multiplying by 10 will definitely overflow - If
<span>result == INT_MAX / 10</span>, check the next digit: - In the case of positive numbers, if the digit is > 7, it will overflow (because the last digit of 2147483647 is 7)
- In the case of negative numbers, if the digit is > 8, it will overflow (because the last digit of -2147483648 is 8)
Complete CodeHeader Files
#include <stdio.h>#include <ctype.h> // For isspace() function#include <limits.h> // For INT_MAX and INT_MIN
Implementation Interface
int my_atoi(const char* str) { int result = 0; // 1. Handle null pointer if (str == NULL) { return result; } // 2. Skip leading whitespace // Index int i = 0; while (isspace(str[i])) { i++; } // 3. Handle positive and negative signs // Sign, 1 for positive, -1 for negative int sign = 1; if (str[i] == '+' || str[i] == '-') { sign = (str[i] == '-') ? -1 : 1; i++; } // 4. Convert numeric characters while (str[i] >= '0' && str[i] <= '9') { // Check for overflow if (result > INT_MAX / 10 || (result == INT_MAX / 10 && str[i] - '0' > 7)) { return (sign == 1) ? INT_MAX : INT_MIN; } // Accumulate result result = result * 10 + (str[i] - '0'); i++; } // 5. Return signed result return result * sign;}
Test Main Function
// Test functionint main() { // Test cases const char* testCases[] = { "123", // Normal positive number "-123", // Normal negative number "+456", // With positive sign " 789", // Leading spaces "12a34", // Non-numeric in the middle "2147483647", // INT_MAX "2147483648", // Exceeds INT_MAX "-2147483648", // INT_MIN "-2147483649", // Less than INT_MIN " ", // All spaces NULL, // Null pointer "abc123" // Non-numeric at the start }; // Calculate length int numCases = sizeof(testCases) / sizeof(testCases[0]); for (int i = 0; i < numCases; i++) { int value = my_atoi(testCases[i]); printf("Input: \"%s\" -> Output: %d\n", (testCases[i] == NULL) ? "NULL" : testCases[i], value); } return 0;}
Version of the Interface Without Any Checks
This interface can only handle positive numbers (“123”) or negative numbers (“-123”) and cannot include other characters; encountering other characters will prematurely end the loop.SummaryThe key to implementing a string to integer conversion function is:
- Comprehensively consider various edge cases
- Correctly handle signs and whitespace characters
- Strict overflow checks
- Stop conversion upon encountering non-numeric characters
The implementation in this article mimics the standard library<span>atoi</span> function but adds more explicit overflow handling. Understanding the implementation of this function helps grasp important programming skills such as string processing, boundary checking, and overflow control.