The wcstoul
function in C interprets a given wide string as an unsigned integral number of a specified base. All characters up to the first non-numeric character are converted to an unsigned long integer
. The wcstoul
function ignores any leading whitespace.
Note: The
unsigned long
data type can take on any value between to .
The process is illustrated below:
Note: A wide string is comprised of characters from the Unicode character set.
To use the wcstoul
function, you will need to include the <wchar.h>
library in the program, as shown below:
#include <wchar.h>
The prototype of the wcstoul
function is shown below:
unsigned long int wcstoul(const wchar_t *str, wchar_t **str_end, int base);
The wcstoul
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 {,,,…,,}.
If the conversion is successful, the wcstoul
function returns an unsigned long integer
value; otherwise, it returns .
The code below shows how the wcstoul
function works in C:
#include <stdio.h>#include <wchar.h>int main() {// initilaizing stringswchar_t str[] = L"2021Educative22";wchar_t* str_end;unsigned long int result;// converting string to long long intresult = wcstoul(str, &str_end, 10);// output resultsprintf("The converted unsigned integral number is %lu.\n", result);printf("The remaining string is \'%ls\'.", str_end);return 0;}
First, the code initializes the wide string we want to convert. 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 wcstoul
function in line 12 proceeds to convert the given wide string, “2021Educative22”, to an unsigned long integer
. For this example, the decimal number system (base ) is used.
Since the first characters (“2021”) represent valid numeric characters, the conversion is successful and the wcstoul
function returns the value . The remaining string, “Educative22”, is stored at the location pointed to by str_end
.
Free Resources