乐闻世界logo
搜索文章和话题

What is the correct usage of strtol in C?

1个答案

1

strtol Function Introduction

The strtol function converts a string to a long integer in C. Its prototype is defined in the <stdlib.h> header file:

c
long int strtol(const char *str, char **endptr, int base);
  • str is a pointer to the string to be converted.
  • endptr is a pointer to a pointer that stores the address of the first character remaining after conversion.
  • base is the radix for conversion, specified as a number between 2 and 36 or the special value 0.

Correct Usage of strtol

  1. Specify the appropriate radix: The base parameter determines the radix of the string. For example, if the string begins with '0x' or '0X', set base to 16. If base is 0, strtol automatically infers the radix based on the prefix: '0x' for hexadecimal, '0' for octal, or no prefix for decimal.

  2. Error Handling: Always check for and handle potential errors when using strtol:

    • Invalid Input: If no conversion occurs, strtol returns 0, which can be confirmed by checking if endptr equals str.
    • Overflow: If the converted value exceeds the range of long int, strtol returns LONG_MAX or LONG_MIN and sets errno to ERANGE.
  3. Use endptr to identify the conversion endpoint: endptr indicates the position after the numeric part, which is crucial for parsing complex strings. You can then process the remaining string based on this pointer.

Example

Consider a string containing mixed data where we want to extract and convert the integer value:

c
#include <stdio.h> #include <stdlib.h> #include <errno.h> int main() { const char *data = "123ABC456"; char *endptr; long int value; errno = 0; // Reset errno to detect overflow value = strtol(data, &endptr, 10); if (endptr == data) { printf("No digits were found\n"); } else { printf("The number (long int) is %ld\n", value); } if (errno == ERANGE) { if (value == LONG_MAX) { printf("Overflow occurred: value is equal to LONG_MAX\n"); } else if (value == LONG_MIN) { printf("Underflow occurred: value is equal to LONG_MIN\n"); } } printf("Remaining text is: %s\n", endptr); return 0; }

In this example, the program correctly converts the string "123ABC456" to the long integer 123 and identifies "ABC456" as the remaining text.

Summary

As demonstrated, strtol is not limited to simple numeric conversions; it can handle complex string parsing and effectively manage error detection and handling. Using strtol correctly enhances program robustness and flexibility when processing external input.

2024年6月29日 12:07 回复

你的答案