C++ cinttypes::strtoimax() Function



The std::cinttypes::strtoimax() function in C++, is used to convert a string representation of an integer into a value of type intmax_t. It provides a way to handle conversions of large integer values across various bases, such as binary, decimal or hexadecimal.

This function also handles out-of-range values by setting the errno to ERANGE.

Syntax

Following is the syntax for std::cinttypes::strtoimax() function.

strtoimax( const char* nptr, char** endptr, int base );
or
strtoumax( const char* nptr, char** endptr, int base );

Parameters

  • nptr − It indicates the pointer to the null-terminated byte string to be interpreted.
  • endptr − It indicates the pointer to a pointer to character.
  • base − It indicates the base of the interpreted integer value.

Return value

This function returns an integer value corresponding to the contents of str if it is successful.

Example 1

Let's look at the following example, where we are going to consider the basic conversion.

#include <iostream>
#include <cinttypes>
int main() {
   const char * a = "12123";
   char * b;
   intmax_t x = std::strtoimax(a, & b, 10);
   std::cout << "Result : " << x << "\n";
   return 0;
}

Output

Output of the above code is as follows −

Result : 12123

Example 2

Consider the following example, where we are going to perform the hexadecimal conversion.

#include <iostream>
#include <cinttypes>
int main() {
   const char * a = "7F";
   char * b;
   intmax_t x = std::strtoimax(a, & b, 16);
   std::cout << "Result : " << x;
   return 0;
}

Output

Following is the output of the above code −

Result : 127
cpp_cinttypes.htm
Advertisements