Hàm atoi convert string thành số nguyên

int atoi(const char *str);
long atol(const char *str);

Parameter:

str: chuỗi kí tự cần được convert

Remark:

Hàm atoi( ) (atol( ))convert string (kiểu char*) thành số nguyên int (long)

  • Hàm sẽ trả về 0 nếu convert không thành công
  • Nếu bị overflow, hàm sẽ trả về hằng số LONG_MIN hoặc LONG_MAX, errno sẽ được set hằng số

Ví dụ:

#include "stdio.h"
#include "conio.h"
#include "stdlib.h"
#include <errno.h>

void main( void )
{
    char *str = NULL;
    int value = 0;

    // An example of the atoi function.
    str = " -2309 ";
    value = atoi( str );
    printf( "Function: atoi( \"%s\" ) = %d\n", str, value );

    // Another example of the atoi function.
    str = "31412764";
    value = atoi( str );
    printf( "Function: atoi( \"%s\" ) = %d\n", str, value );

    // Another example of the atoi function 
    // with an overflow condition occuring.
    str = "3336402735171707160320";
    value = atoi( str );
    printf( "Function: atoi( \"%s\" ) = %d\n", str, value );
    if (errno == ERANGE)
    {
        printf("Overflow condition occurred.\n");
    }
    getch();
}

Kết quả:

Hàm atoi convert string thành số nguyên

Be the first to comment

Leave a Reply