📜  strtol c (1)

📅  最后修改于: 2023-12-03 15:05:23.409000             🧑  作者: Mango

Introduction to strtol() function in C

strtol() is a standard library function in C programming language that converts a string of characters to a long integer value. It is defined in the stdlib.h header file and takes three arguments:

long int strtol(const char *str, char **endptr, int base);
  • The first argument 'str' is the string to be converted.
  • The second argument 'endptr' is a pointer to a character that will be set to the first invalid character in 'str', or to 'str' itself if no invalid characters were found.
  • The third argument 'base' specifies the number base of the conversion.

Here's an example of how to use strtol():

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

int main() {
    char str[] = "1234567890";
    char *endptr;
    long int num;

    num = strtol(str, &endptr, 10);
    printf("Converted string is %ld\n", num);

    return 0;
}

In this example, strtol() function converts the string "1234567890" to a long integer value, which is then assigned to the variable 'num'. The 'endptr' pointer is set to point to the last character in 'str' because all characters in the string were valid digits. The third argument '10' specifies that the conversion is in base-10 (decimal).

It's important to note that strtol() function is a safer and more robust way to convert strings to integers than the atoi() function because it can handle error conditions and invalid input.