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

ฟังก์ชัน strtol() ใน C++: แปลง String เป็น Long Integer

strtol() ใน <cstdlib> แปลง String เป็น long int รองรับ Base 2-36

Syntax

long int strtol(const char* str, char** endptr, int base);

Parameters

  • str: สตริง Input
  • endptr: Pointer ที่จะถูกตั้งให้ชี้ตัวอักษรถัดจากตัวสุดท้ายที่แปลงได้ (อาจเป็น NULL)
  • base: ฐานเลข (0, 2-36). Base 0 = Auto-detect (0x=Hex, 0=Octal, Else=Decimal)

ตัวอย่าง: Base 10 (Decimal)

#include <iostream>
#include <cstdlib>
using namespace std;

int main() {
    char str1[] = "777HelloWorld";
    char str2[] = "565Hello";
    char* end;
    int base = 10;

    long val1 = strtol(str1, &end, base);
    cout << "String: " << str1 << endl;
    cout << "Value: " << val1 << endl;
    cout << "Remaining: " << end << endl; // "HelloWorld"

    long val2 = strtol(str2, &end, base);
    cout << "\nString: " << str2 << endl;
    cout << "Value: " << val2 << endl;
    cout << "Remaining: " << end << endl; // "Hello"

    return 0;
}

ผลลัพธ์

String: 777HelloWorld
Value: 777
Remaining: HelloWorld

String: 565Hello
Value: 565
Remaining: Hello

ตัวอย่าง: Base 16 (Hexadecimal)

char str1[] = "5EHelloWorld"; // 5E hex = 94 dec
char str2[] = "125Hello";     // 125 hex = 293 dec
int base = 16;
// Output: 94 and 293

Error Handling

  • Overflow: คืน LONG_MAX หรือ LONG_MIN ตั้ง errno = ERANGE
  • No conversion: คืน 0, endptr = str
  • Whitespace นำหน้าถูกข้ามอัตโนมัติ

C++ Modern Alternative

// C++11 stoi/stol (Exception-based)
string s = "123abc";
size_t pos;
long val = stol(s, &pos, 10); // val=123, pos=3

// C++17 from_chars (No exception, Fast)
char str[] = "123abc";
long val;
auto [ptr, ec] = from_chars(str, str+strlen(str), val, 10);

ฟังก์ชันที่เกี่ยวข้อง

  • strtoul - Unsigned long
  • strtoll - Long long
  • strtod - Double