Hàm strtol tách số từ string dựa vào cơ số

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

Parameter:

nptr: chuỗi kí tự đầu vào cần convert

endptr: con trỏ trỏ tới kí tự không thể convert được.

base: cơ số (  2: binary, 8: octal, 10: decimal,…)

Remark:

Hàm strtol( ) convert chuỗi kí tự (kiểu char*) dựa vào cơ số và trả về số kiểu long.

  • Hàm trả về 0 nếu nptr = NULL.
  • Nếu overflow xảy ra, hàm trả về LONG_MAX LONG_MIN
  • Trong cả 2 trường hợp overflow, underflow, errno được set ERANGE

Ví dụ:

#include "stdio.h"
#include "conio.h"
#include "stdlib.h"

void main( void )
{
    char *string, *stopstring;
    long l;
    int base;

    string = "-10110134This stopped it";
    l = strtol( string, &stopstring, 2);
    printf("string = %s\n", string );
    printf("strtol = %ld\n", l );  //101101 = 45
    printf("Stopped scan at: %s\n\n", stopstring );

    l = strtol( string, &stopstring, 10);
    printf("string = %s\n", string );
    printf("strtol = %ld\n", l );
    printf("Stopped scan at: %s\n\n", stopstring );
    getch();
} 

Kết quả:

Hàm strtol tách số từ string dựa vào cơ số
Hàm strtol tách số từ string dựa vào cơ số

Be the first to comment

Leave a Reply