Related Tags

c

# What is wcstoll in C?

Talha Ashar

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

The wcstoll function in C interprets a given wide string as an integral number of a specified base. All characters up to the first non-numeric character are converted to a long long integer. The wcstoll function ignores any leading whitespaces.

The process is illustrated below:

Note: A wide string is comprised of characters from the Unicode character set.

To use the wcstoll function, you will need to include the <wchar.h> library in the program, as shown below:

#include <wchar.h>


The prototype of the wcstoll function is shown below:

long long int wcstoll(const wchar_t *str, wchar_t **str_end, int base);


## Parameters

The wcstoll function takes the following objects as parameters:

• str: The wide string to be converted
• str_end: A pointer that references the characters after the last valid numeric character in str. This parameter may also be a null pointer.
• base: The base of the integral value.

Note: The set of values for the base is {$0$,$2$,$3$,…,$35$,$36$}.

## Return value

If the conversion is successful, the wcstoll function returns a long long integer value. Otherwise, It returns $0$.

## Example

The code below shows how the wcstoll function works in C:

#include <stdio.h>
#include <wchar.h>

int main() {

// initilaizing strings
wchar_t str[] = L"2021Educative22";
wchar_t* str_end;
long long int result;

// converting string to long long int
result = wcstoll(str, &str_end, 10);

// output results
printf("The converted integral number is %llu.\n", result);
printf("The remaining string is \'%ls\'.", str_end);

return 0;
}

## Explanation

First, the wide string we want to convert is initialized. The ‘L’ identifier in Line 7 informs the compiler that the Unicode character set is being used. The str_end pointer will contain the string that remains after conversion.

The wcstoll function in Line 12 proceeds to convert the given wide string, “2021Educative22”, to a long long integer. For this example, the decimal number system (base $10$) is used.

Since the first $4$ characters (“2021”) represent valid numeric characters, the conversion is successful, and the wcstoll function returns the value $2021$. The remaining string (“Educative22”) is stored at the location pointed to by str_end.

RELATED TAGS

c

CONTRIBUTOR

Talha Ashar