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

ฟังก์ชัน strtod() ใน C/C++: แปลง String เป็น Double

ฟังก์ชัน strtod() (String to Double) แปลง String เป็น Floating-point Number (double) อยู่ใน Header <stdlib.h> เป็นมาตรฐาน C

ไวยากรณ์

#include <stdlib.h>
double strtod(const char *nptr, char **endptr);
  • nptr - String ที่จะแปลง
  • endptr - Output Parameter: ชี้ไปที่ตัวอักษรแรกที่ไม่ได้ Parse (Optional, ส่ง NULL ได้)
  • คืนค่า: ค่า Double ที่แปลงได้, 0.0 ถ้าแปลงไม่ได้

ตัวอย่าง

#include <stdio.h>
#include <stdlib.h>

int main() {
    char s[] = "8.28 is a number";
    char *endptr;
    double result;
    
    result = strtod(s, &endptr);
    
    printf("Converted number: %lf\n", result);      // 8.280000
    printf("End pointer at: '%s'\n", endptr);       // " is a number"
    printf("Characters parsed: %td\n", endptr - s);  // 4
    
    return 0;
}

ผลลัพธ์

Converted number: 8.280000
End pointer at: ' is a number'
Characters parsed: 4

รูปแบบ String ที่ Parse ได้ (Grammar)

[whitespace] [sign] [digits] [.digits] [ {e|E} [sign] digits ]

Examples:
"123"        → 123.0
"-45.67"     → -45.67
"  +3.14"    → 3.14
"1.5e2"      → 150.0
"1E-3"       → 0.001
"INF"        → Infinity (C99)
"NAN"        → NaN (C99)
"0x1.8p3"    → Hex Float (C99): 1.5 * 2^3 = 12.0

Return Values และ Error Handling

สถานการณ์Return Valueendptrerrno
Parse สำเร็จConverted ValueNext Char After NumberUnchanged
No Conversion (No Digits)0.0nptr (Original Pointer)Unchanged
Overflow (Value too Large)HUGE_VAL (±∞)End of Parsed PartERANGE
Underflow (Value too Small)0.0End of Parsed PartERANGE

ตัวอย่าง Error Handling ครบถ้วน

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <math.h>

double parseDouble(const char *str, int *error) {
    char *endptr;
    errno = 0;
    
    double val = strtod(str, &endptr);
    
    if (endptr == str) {
        *error = 1;  // No conversion
        return 0.0;
    }
    
    if (errno == ERANGE) {
        *error = 2;  // Overflow/Underflow
        return val;
    }
    
    // Optional: Check trailing characters
    while (*endptr && isspace((unsigned char)*endptr)) endptr++;
    if (*endptr != '\0') {
        *error = 3;  // Trailing garbage
    }
    
    *error = 0;
    return val;
}

int main() {
    const char *tests[] = {"123.45", "abc", "1e309", "123abc", "  -42.5  "};
    
    for (int i = 0; i < 5; i++) {
        int err;
        double val = parseDouble(tests[i], &err);
        printf("'%s' → %.4f (err=%d)\n", tests[i], val, err);
    }
    return 0;
}

ผลลัพธ์

'123.45' → 123.4500 (err=0)
'abc' → 0.0000 (err=1)
'1e309' → inf (err=2)
'123abc' → 123.0000 (err=3)
'  -42.5  ' → -42.5000 (err=0)

C++ Variants

  • std::strtod - ใน <cstdlib> (C++ Wrapper)
  • std::stod - ใน <string> (C++11, Throws Exceptions)
  • std::from_chars - ใน <charconv> (C++17, No Locale, Fast, No Exceptions)

C++17 from_chars (High Performance)

#include <charconv>
#include <string>
#include <iostream>

int main() {
    std::string s = "3.14159";
    double result;
    
    auto [ptr, ec] = std::from_chars(s.data(), s.data() + s.size(), result);
    
    if (ec == std::errc()) {
        std::cout << "Parsed: " << result << ", Consumed: " << (ptr - s.data()) << "\n";
    } else {
        std::cout << "Parse failed: " << std::to_string((int)ec) << "\n";
    }
    return 0;
}

สรุป

strtod() เป็นฟังก์ชันมาตรฐานสำหรับแปลง String → Double ใน C ให้ End Pointer สำหรับ Parsing ต่อเนื่อง และ Error Handling ผ่าน errno ใน C++ ควรใช้ std::stod หรือ std::from_chars (Performance Critical)