Bird
Raised Fist0
DSA Cprogramming

String to Integer atoi in DSA C

Choose your learning style10 modes available
Mental Model
Convert each character digit in the string to a number and build the integer step by step.
Analogy: Like reading a number on a sign one digit at a time and writing it down to form the full number.
Input string: "  -42abc"
Positions:  [0] [1] [2] [3] [4] [5] [6]
Characters: ' '  '-'  '4'  '2'  'a'  'b'  'c'

Integer building:
result = 0
result = result * 10 + digit

Pointer ↑ at start of string
Dry Run Walkthrough
Input: string: " -42abc"
Goal: Convert the string to integer -42, ignoring trailing non-digit characters
Step 1: Skip leading spaces
Pointer ↑ at '-' (index 2), string: "  -42abc"
Why: Spaces do not affect the number, so we ignore them
Step 2: Check sign character '-' and set sign = -1
Pointer ↑ at '4' (index 3), sign = -1
Why: Minus sign means the number is negative
Step 3: Convert '4' to digit 4 and update result = 0 * 10 + 4 = 4
result = 4, pointer ↑ at '2' (index 4)
Why: First digit of the number
Step 4: Convert '2' to digit 2 and update result = 4 * 10 + 2 = 42
result = 42, pointer ↑ at 'a' (index 5)
Why: Second digit of the number
Step 5: Encounter non-digit 'a', stop parsing
result = 42, pointer at 'a' (index 5)
Why: Non-digit means number ends here
Step 6: Apply sign to result: result = -1 * 42 = -42
final result = -42
Why: Sign affects the final integer value
Result:
final integer = -42
Annotated Code
DSA C
#include <stdio.h>
#include <limits.h>

int myAtoi(const char *str) {
    int i = 0;
    int sign = 1;
    long result = 0;

    // Skip leading spaces
    while (str[i] == ' ') {
        i++;
    }

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

    // Convert digits to integer
    while (str[i] >= '0' && str[i] <= '9') {
        result = result * 10 + (str[i] - '0');

        // Check overflow
        if (sign == 1 && result > INT_MAX) {
            return INT_MAX;
        }
        if (sign == -1 && -result < INT_MIN) {
            return INT_MIN;
        }
        i++;
    }

    return (int)(sign * result);
}

int main() {
    const char *input = "  -42abc";
    int output = myAtoi(input);
    printf("%d\n", output);
    return 0;
}
while (str[i] == ' ') { i++; }
skip all spaces before number
if (str[i] == '-' || str[i] == '+') { sign = (str[i] == '-') ? -1 : 1; i++; }
detect and record sign, move pointer forward
while (str[i] >= '0' && str[i] <= '9') {
process each digit character
result = result * 10 + (str[i] - '0');
build integer by shifting digits left and adding new digit
if (sign == 1 && result > INT_MAX) { return INT_MAX; }
handle positive overflow by clamping
if (sign == -1 && -result < INT_MIN) { return INT_MIN; }
handle negative overflow by clamping
return (int)(sign * result);
apply sign and return final integer
OutputSuccess
-42
Complexity Analysis
Time: O(n) because we scan the string once until non-digit or end
Space: O(1) because we use fixed variables, no extra data structures
vs Alternative: Compared to using built-in functions, this manual parsing avoids overhead and allows custom overflow handling
Edge Cases
empty string
returns 0 because no digits found
DSA C
while (str[i] >= '0' && str[i] <= '9') {
string with only spaces
returns 0 after skipping spaces and finding no digits
DSA C
while (str[i] == ' ') { i++; }
string with number exceeding int max
returns INT_MAX to avoid overflow
DSA C
if (sign == 1 && result > INT_MAX) { return INT_MAX; }
string with number below int min
returns INT_MIN to avoid overflow
DSA C
if (sign == -1 && -result < INT_MIN) { return INT_MIN; }
string with no digits after sign
returns 0 because no digits parsed
DSA C
while (str[i] >= '0' && str[i] <= '9') {
When to Use This Pattern
When you see a problem asking to convert a string to an integer with possible spaces and signs, use the atoi pattern to parse character by character and handle edge cases.
Common Mistakes
Mistake: Not skipping leading spaces before parsing digits
Fix: Add a loop to skip spaces before checking sign or digits
Mistake: Not handling sign character correctly
Fix: Check for '+' or '-' and set sign variable accordingly before parsing digits
Mistake: Not stopping parsing at first non-digit character
Fix: Stop the digit parsing loop when a non-digit is encountered
Mistake: Ignoring integer overflow and underflow
Fix: Check if result exceeds INT_MAX or INT_MIN and clamp accordingly
Summary
Converts a string to an integer by reading digits and applying sign.
Use when you need to parse numbers from strings with spaces and signs.
The key is to process characters one by one, handle sign, and stop at first non-digit.

Practice

(1/5)
1. What does the atoi function do in C programming?
easy
A. Checks if a string contains only digits
B. Converts a string representing a number into an integer
C. Calculates the length of a string
D. Converts an integer into a string

Solution

  1. Step 1: Understand the purpose of atoi

    The atoi function stands for ASCII to integer, which means it converts a string of digits into an integer value.
  2. Step 2: Compare options with definition

    Only Converts a string representing a number into an integer correctly describes this conversion from string to integer.
  3. Final Answer:

    Converts a string representing a number into an integer -> Option B
  4. Quick Check:

    atoi = string to integer conversion [OK]
Hint: Remember atoi means ASCII to integer conversion [OK]
Common Mistakes:
  • Confusing atoi with itoa (integer to ASCII)
  • Thinking atoi calculates string length
  • Assuming atoi validates string digits
2. Which of the following is the correct syntax to use atoi in C?
easy
A. int num = atoi(char *str);
B. int num = atoi();
C. int num = atoi(int str);
D. int num = atoi(str);

Solution

  1. Step 1: Check function parameter type

    The atoi function takes a single argument of type const char *, which is a string pointer.
  2. Step 2: Validate correct syntax

    int num = atoi(str); correctly shows calling atoi with a string variable str without specifying type in call.
  3. Final Answer:

    int num = atoi(str); -> Option D
  4. Quick Check:

    atoi takes string variable as argument [OK]
Hint: Call atoi with just the string variable name [OK]
Common Mistakes:
  • Including type in function call parentheses
  • Calling atoi without arguments
  • Passing integer instead of string
3. What will be the output of the following C code?
char str[] = "-123abc";
int val = atoi(str);
printf("%d", val);
medium
A. -123
B. 0
C. 123
D. Error

Solution

  1. Step 1: Analyze atoi behavior with mixed string

    atoi converts initial numeric part including sign until non-digit character. Here, "-123" is converted, stops at 'a'.
  2. Step 2: Determine output value

    So, val becomes -123 and printf prints -123.
  3. Final Answer:

    -123 -> Option A
  4. Quick Check:

    atoi stops at first non-digit, returns -123 [OK]
Hint: atoi reads number until first non-digit character [OK]
Common Mistakes:
  • Expecting atoi to ignore leading sign
  • Thinking atoi returns 0 on trailing letters
  • Assuming runtime error due to letters
4. Identify the error in this code snippet using atoi:
char *str = NULL;
int num = atoi(str);
printf("%d", num);
medium
A. Passing NULL pointer to atoi causes undefined behavior
B. Missing header file
C. atoi cannot convert strings with digits
D. No error, code runs fine

Solution

  1. Step 1: Check argument passed to atoi

    The code passes a NULL pointer to atoi, which expects a valid string pointer.
  2. Step 2: Understand consequences of NULL argument

    Passing NULL leads to undefined behavior, often causing a crash or runtime error.
  3. Final Answer:

    Passing NULL pointer to atoi causes undefined behavior -> Option A
  4. Quick Check:

    atoi needs valid string pointer, NULL causes error [OK]
Hint: Never pass NULL to atoi; always check string pointer [OK]
Common Mistakes:
  • Ignoring NULL pointer checks
  • Assuming atoi handles NULL safely
  • Confusing missing header with runtime error
5. You want to convert a string to integer but also detect if the string contains invalid characters after the number. Which approach is best in C?
hard
A. Use atoi and then check the rest of the string manually
B. Use atoi and assume input is always valid
C. Use strtol which provides end pointer to check leftover characters
D. Use printf to convert string to integer

Solution

  1. Step 1: Understand limitation of atoi

    atoi converts initial number but does not provide info about leftover invalid characters.
  2. Step 2: Use strtol for better control

    strtol converts string to long and returns pointer to first invalid character, allowing validation.
  3. Step 3: Choose best approach

    Use strtol which provides end pointer to check leftover characters uses strtol with end pointer to detect invalid trailing characters safely.
  4. Final Answer:

    Use strtol which provides end pointer to check leftover characters -> Option C
  5. Quick Check:

    strtol + end pointer = safe string to int with validation [OK]
Hint: Use strtol with end pointer to detect invalid chars [OK]
Common Mistakes:
  • Relying only on atoi for input validation
  • Ignoring leftover characters after number
  • Using printf incorrectly for conversion
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard