Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

เขียนฟังก์ชัน atoi() เองใน C++

ฟังก์ชัน atoi() คืออะไร?

ฟังก์ชัน atoi() (ASCII to Integer) ใน C/C++ ใช้แปลงสตริง (string) เป็นจำนวนเต็ม (integer) ประกาศอยู่ใน <cstdlib> (C) หรือ <cstdlib> (C++)

Syntax

int atoi(const char* str);

พฤติกรรมมาตรฐาน

  • ข้าม whitespace นำหน้า (leading whitespace)
  • อ่าน sign (+/-) ถ้ามี
  • อ่านตัวเลขต่อเนื่องจนกว่าจะเจอ non-digit
  • คืนค่าจำนวนเต็มที่แปลงได้
  • หากไม่มีตัวเลข คืนค่า 0
  • พฤติกรรม undefined behavior หาก overflow (C++11 กำหนดให้เป็น implementation-defined)

Implementation ของ atoi() เอง

#include <iostream>
#include <climits>  // สำหรับ INT_MAX, INT_MIN
using namespace std;

bool isNumericChar(char c) {
    return (c >= '0' && c <= '9');
}

int myAtoi(const char* str) {
    if (!str || *str == '\0') return 0;
    
    // 1. ข้าม leading whitespace
    while (*str == ' ' || *str == '\t' || *str == '\n' || 
           *str == '\r' || *str == '\v' || *str == '\f') {
        str++;
    }
    
    // 2. เช็ค sign
    int sign = 1;
    if (*str == '-') {
        sign = -1;
        str++;
    } else if (*str == '+') {
        str++;
    }
    
    // 3. แปลงตัวเลข
    long long result = 0;  // ใช้ long long กัน overflow ระหว่างคำนวณ
    
    while (isNumericChar(*str)) {
        int digit = *str - '0';
        
        // Overflow check
        if (sign == 1 && (result > INT_MAX / 10 || 
            (result == INT_MAX / 10 && digit > INT_MAX % 10))) {
            return INT_MAX;
        }
        if (sign == -1 && (result > (unsigned)INT_MAX / 10 || 
            (result == (unsigned)INT_MAX / 10 && digit > (unsigned)INT_MAX % 10 + 1))) {
            return INT_MIN;
        }
        
        result = result * 10 + digit;
        str++;
    }
    
    return sign * result;
}

int main() {
    char str[] = "-32491841";
    int intVal = myAtoi(str);
    cout << "The integer equivalent of the given string is: " << intVal;
    return 0;
}

ผลลัพธ์

The integer equivalent of the given string is: -32491841

Test Cases

InputOutputคำอธิบาย
"42"42ปกติ
" -42"-42leading space + negative
"4193 with words"4193หยุดที่ non-digit
"words and 987"0ไม่มีตัวเลขนำหน้า
"-91283472332"INT_MINunderflow
"+1"1explicit positive
""0empty string

C++ Modern Alternative

#include <string>
#include <stdexcept>

// ใช้ std::stoi (C++11) - มี exception handling
try {
    int val = stoi("123");
} catch (const invalid_argument& e) {
    // ไม่ใช่ตัวเลข
} catch (const out_of_range& e) {
    // overflow
}

// ใช้ std::from_chars (C++17) - ไม่มี exception, เร็วกว่า
#include <charconv>
int val;
auto result = from_chars(str, str + strlen(str), val);
if (result.ec == errc()) { /* success */ }

สรุป

การ implement atoi เองเป็นการฝึกฝนที่ดีสำหรับการทำ string parsing, overflow handling, และ edge cases ใน production code ควรใช้ std::from_chars (C++17) ซึ่งเร็วที่สุด ไม่มี exception และมี error handling ชัดเจนที่สุด