C++ cinttypes::wcstoimax() Function



The std::cinttypes::wcstoimax() function in C++, converts a wide character string to an integer. It accepts three arguments: the wide character string, a pointer for tracking the conversions end poind and the base for conversion. It returns the converted value or returns INTMAX_MAX/INTMAX_MIN in case of overflow.

Syntax

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

wcstoimax( const wchar_t* nptr, wchar_t** endptr, int base );
or
wcstoumax( const wchar_t* nptr, wchar_t** 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 the integer value corresponding to the contents of str on success.

Example 1

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

#include <iostream>
#include <cwchar>
#include <cinttypes>
int main() {
   const wchar_t * a = L "11211";
   wchar_t * b;
   intmax_t x = wcstoimax(a, & b, 10);
   std::wcout << L "Result : " << x << L "\n";
   return 0;
}

Output

Output of the above code is as follows −

Result : 11211

Example 2

Consider the following example, wher we are going to perform the hexa-decimal conversion.

#include <iostream>
#include <cwchar>
#include <cinttypes>
int main() {
   const wchar_t * x = L "1A6A";
   wchar_t * y;
   intmax_t a = wcstoimax(x, & y, 16);
   std::wcout << L "Result : " << a << L "\n";
   return 0;
}

Output

Following is the output of the above code −

Result : 6762

Example 3

In the following example, we are going to perform the partial conversion with invalid characters.

#include <iostream>
#include <cwchar>
#include <cinttypes>
int main() {
   const wchar_t * x = L "1121abc";
   wchar_t * y;
   intmax_t a = wcstoimax(x, & y, 10);
   std::wcout << L "Converted value: " << a << L "\n";
   std::wcout << L "Remaining string: " << y << L "\n";
   return 0;
}

Output

If we run the above code it will generate the following output −

Converted value: 1121
Remaining string: abc
cpp_cinttypes.htm
Advertisements