Bird
Raised Fist0
DSA C++programming

String to Integer atoi in DSA C++

Choose your learning style10 modes available
Mental Model
Convert a string of characters into a number by reading each digit one by one and building the number step by step.
Analogy: Like reading a price tag digit by digit and writing down the total price as a number in your notebook.
string: "  -42abc"
index -> 0 1 2 3 4 5 6
chars: ' ' '-' '4' '2' 'a' 'b' 'c'
result: 0
sign: +1
↑ index points to first char
Dry Run Walkthrough
Input: string: " -42abc"
Goal: Convert the initial numeric part of the string into an integer, handling spaces and sign, stopping at first non-digit
Step 1: skip leading spaces
index -> 2
chars: ' ' ' ' ['-'] '4' '2' 'a' 'b' 'c'
result: 0
sign: +1
Why: Ignore spaces before the number to find where the number starts
Step 2: detect sign '-' and set sign to -1
index -> 3
chars: ' ' ' ' '-' ['4'] '2' 'a' 'b' 'c'
result: 0
sign: -1
Why: Identify if the number is negative or positive
Step 3: read digit '4', update result = 0 * 10 + 4 = 4
index -> 4
chars: ' ' ' ' '-' '4' ['2'] 'a' 'b' 'c'
result: 4
sign: -1
Why: Build the number by adding the digit
Step 4: read digit '2', update result = 4 * 10 + 2 = 42
index -> 5
chars: ' ' ' ' '-' '4' '2' ['a'] 'b' 'c'
result: 42
sign: -1
Why: Continue building the number
Step 5: stop reading at non-digit 'a'
index -> 5
chars: ' ' ' ' '-' '4' '2' ['a'] 'b' 'c'
result: 42
sign: -1
Why: Stop parsing when non-digit character is found
Result:
final number = -42
Annotated Code
DSA C++
#include <iostream>
#include <string>
#include <climits>

class Solution {
public:
    int myAtoi(const std::string& s) {
        int index = 0, n = s.size();
        while (index < n && s[index] == ' ') {
            index++; // skip spaces
        }
        int sign = 1;
        if (index < n && (s[index] == '+' || s[index] == '-')) {
            sign = (s[index] == '-') ? -1 : 1;
            index++; // move past sign
        }
        long result = 0;
        while (index < n && isdigit(s[index])) {
            int digit = s[index] - '0';
            result = result * 10 + digit; // build number
            if (result * sign > INT_MAX) return INT_MAX; // clamp to INT_MAX
            if (result * sign < INT_MIN) return INT_MIN; // clamp to INT_MIN
            index++;
        }
        return (int)(result * sign);
    }
};

int main() {
    Solution sol;
    std::string input = "  -42abc";
    std::cout << sol.myAtoi(input) << std::endl;
    return 0;
}
while (index < n && s[index] == ' ') { index++; // skip spaces }
skip all leading spaces to find start of number
if (index < n && (s[index] == '+' || s[index] == '-')) { sign = (s[index] == '-') ? -1 : 1; index++; // move past sign }
detect and record sign of number
while (index < n && isdigit(s[index])) { int digit = s[index] - '0'; result = result * 10 + digit; // build number if (result * sign > INT_MAX) return INT_MAX; // clamp to INT_MAX if (result * sign < INT_MIN) return INT_MIN; // clamp to INT_MIN index++; }
read digits one by one, build number, clamp if overflow
return (int)(result * sign);
return final signed integer
OutputSuccess
-42
Complexity Analysis
Time: O(n) because we scan the string once from left to right
Space: O(1) because we use only a few variables regardless of input size
vs Alternative: Compared to parsing with built-in functions, this manual method handles invalid input and overflow safely with predictable behavior
Edge Cases
empty string
returns 0 because no digits found
DSA C++
while (index < n && s[index] == ' ') { index++; }
string with only spaces
returns 0 after skipping all spaces
DSA C++
while (index < n && s[index] == ' ') { index++; }
string with sign but no digits, e.g. "-"
returns 0 because no digits after sign
DSA C++
while (index < n && isdigit(s[index])) { ... }
number exceeding int max, e.g. "9999999999"
returns INT_MAX to prevent overflow
DSA C++
if (result * sign > INT_MAX) return INT_MAX;
number below int min, e.g. "-9999999999"
returns INT_MIN to prevent overflow
DSA C++
if (result * sign < INT_MIN) return INT_MIN;
When to Use This Pattern
When you see a problem asking to convert a string to a number with rules about spaces, signs, and invalid characters, reach for the String to Integer atoi pattern because it carefully parses character by character with checks.
Common Mistakes
Mistake: Not skipping leading spaces before parsing digits
Fix: Add a loop to skip all spaces before processing sign or digits
Mistake: Ignoring sign character and always assuming positive
Fix: Check for '+' or '-' sign and record it before reading digits
Mistake: Not stopping parsing at first non-digit character
Fix: Stop reading digits as soon as a non-digit character is encountered
Mistake: Not handling integer overflow and underflow
Fix: Check if the number exceeds INT_MAX or INT_MIN and clamp accordingly
Summary
Converts a string into an integer by reading digits, handling spaces and sign.
Use when you need to safely parse numbers from strings with possible extra characters.
The key is to read character by character, skip spaces, handle sign, build number, and stop at first invalid character.

Practice

(1/5)
1. What does the atoi function do in C++?
easy
A. Converts a string representing a number into an integer
B. Converts an integer into a string
C. Sorts characters in a string alphabetically
D. Calculates the length of a string

Solution

  1. Step 1: Understand the purpose of atoi

    The function atoi stands for ASCII to integer and converts a numeric string to an integer value.
  2. Step 2: Differentiate from other string functions

    It does not convert integers to strings, sort strings, or calculate string length.
  3. Final Answer:

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

    atoi = string to int conversion [OK]
Hint: Remember atoi means ASCII to integer conversion [OK]
Common Mistakes:
  • Confusing atoi with itoa (integer to string)
  • Thinking atoi sorts or measures strings
  • Assuming atoi handles non-numeric strings safely
2. Which of the following is the correct syntax to use atoi in C++?
easy
A. int num = atoi("1234");
B. int num = atoi(1234);
C. int num = atoi('1234');
D. int num = atoi(\"1234\");

Solution

  1. Step 1: Check the parameter type for atoi

    The atoi function expects a C-style string (const char*), so the argument must be a string literal like "1234".
  2. Step 2: Analyze each option

    int num = atoi("1234"); passes a string literal correctly. int num = atoi(1234); passes an integer, which is invalid. int num = atoi('1234'); uses single quotes, which denote a char, not a string. int num = atoi(\"1234\"); has escaped quotes incorrectly.
  3. Final Answer:

    int num = atoi("1234"); -> Option A
  4. Quick Check:

    atoi needs a string literal argument [OK]
Hint: atoi requires a string literal, not a number or char [OK]
Common Mistakes:
  • Passing integer instead of string
  • Using single quotes instead of double quotes
  • Incorrect escaping of quotes
3. What will be the output of the following C++ code?
char str[] = "-42abc";
int val = atoi(str);
std::cout << val << std::endl;
medium
A. 0
B. Runtime error
C. 42
D. -42

Solution

  1. Step 1: Understand atoi behavior with non-digit characters

    atoi converts the initial part of the string that forms a valid integer. It stops reading when it encounters a non-digit after the number.
  2. Step 2: Analyze the string "-42abc"

    It starts with '-', then '4', '2' which form -42. The characters 'a', 'b', 'c' are ignored after the number.
  3. Final Answer:

    -42 -> Option D
  4. Quick Check:

    atoi stops at first non-digit after number [OK]
Hint: atoi reads number until non-digit character [OK]
Common Mistakes:
  • Expecting atoi to parse entire string including letters
  • Assuming atoi returns 0 for strings with trailing letters
  • Thinking it throws runtime error on letters
4. Identify the error in the following code snippet that uses atoi:
std::string s = "123";
int num = atoi(s);
std::cout << num << std::endl;
medium
A. Missing header file for atoi
B. atoi requires integer argument
C. Cannot pass std::string directly to atoi
D. No error, code runs fine

Solution

  1. Step 1: Check parameter type for atoi

    atoi expects a C-style string (const char*), but s is a std::string object.
  2. Step 2: Correct usage

    To use atoi with std::string, call s.c_str() to get a C-style string.
  3. Final Answer:

    Cannot pass std::string directly to atoi -> Option C
  4. Quick Check:

    atoi needs const char*, not std::string [OK]
Hint: Use s.c_str() to convert std::string for atoi [OK]
Common Mistakes:
  • Passing std::string directly to atoi
  • Ignoring need for c_str() method
  • Assuming atoi accepts std::string
5. You want to convert a string to integer but also handle invalid inputs safely without crashing. Which approach is best in C++?
hard
A. Use atoi and check if result is zero to detect errors
B. Use stoi inside try-catch block to catch exceptions
C. Use atoi and ignore invalid inputs
D. Use printf to print the string and guess the number

Solution

  1. Step 1: Understand limitations of atoi

    atoi returns 0 for invalid inputs but cannot distinguish between actual zero and error, so it is unsafe for error handling.
  2. Step 2: Use stoi with exception handling

    stoi throws exceptions on invalid input, allowing safe detection and handling of errors using try-catch blocks.
  3. Final Answer:

    Use stoi inside try-catch block to catch exceptions -> Option B
  4. Quick Check:

    stoi with try-catch is safe for invalid input [OK]
Hint: Use stoi with try-catch for safe string to int conversion [OK]
Common Mistakes:
  • Relying on atoi to detect invalid input
  • Ignoring exceptions from stoi
  • Using printf to guess numbers
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