Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Hàm strtol() trong C++ - Chuyển chuỗi sang long int


strtol() từ <cstdlib> chuyển đổi chuỗi ký tự sang long int với cơ số (base) tùy chọn, báo lỗi qua con trỏ endptr.

Cú pháp

long strtol(const char* str, char** endptr, int base);
  • str: Chuỗi đầu vào.
  • endptr: Nếu không NULL, trỏ đến ký tự đầu tiên KHÔNG được chuyển đổi.
  • base: Cơ số (2-36). Nếu 0: tự động nhận diện (0x=hex, 0=oct, khác=dec).

Ví dụ mã nguồn

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

void parse(const char* s, int base = 10) {
    char* end;
    errno = 0;
    long val = strtol(s, &end, base);
    
    cout << "Chuoi: '" << s << "' (base " << base << ")\n";
    if (errno == ERANGE) cout << "  -> Tran so (ERANGE)\n";
    else if (end == s) cout << "  -> Khong co so hop le\n";
    else {
        cout << "  -> Gia tri: " << val << '\n';
        cout << "  -> Con lai: '" << end << "'\n";
    }
    cout << '\n';
}

int main() {
    parse("1234");
    parse("  -567  ");
    parse("100abc");
    parse("0xFF", 0);     // Tự động hex
    parse("077", 0);      // Tự động octal
    parse("ZZ", 36);      // Base 36 (Z=35)
    parse("9999999999999999999"); // Overflow
    return 0;
}

Đầu ra

Chuoi: '1234' (base 10)
  -> Gia tri: 1234
  -> Con lai: ''

Chuoi: '  -567  ' (base 10)
  -> Gia tri: -567
  -> Con lai: '  '

Chuoi: '100abc' (base 10)
  -> Gia tri: 100
  -> Con lai: 'abc'

Chuoi: '0xFF' (base 0)
  -> Gia tri: 255
  -> Con lai: ''

Chuoi: '077' (base 0)
  -> Gia tri: 63
  -> Con lai: ''

Chuoi: 'ZZ' (base 36)
  -> Gia tri: 1295
  -> Con lai: ''

Chuoi: '9999999999999999999' (base 10)
  -> Tran so (ERANGE)

Hàm liên quan

  • strtoul, strtoll, strtoull: unsigned, long long.
  • strtof, strtod, strtold: Cho float/double.
  • C++11: std::stoi, std::stol, std::stoll (ném exception).