The wcstod
function in C interprets a given wide string as a floating-point number. All characters up to the first non-numeric character are converted to a double
. The wcstod
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 wcstod
function, you will need to include the <wchar.h>
library in the program, as shown below:
#include <wchar.h>
The prototype of the wcstod
function is shown below:
double wcstod(const wchar_t *str, wchar_t **str_end);
The wcstod
function takes the following objects as parameters:
str
: The wide string to be converted.str_end
: A pointer to a wide character. The value of this pointer is set to the next character in str
after the last valid floating-point character. This parameter may also be a null pointer.If the conversion is successful, the wcstod
function returns a double value; otherwise, is returned.
If the converted value is out of range, the wcstod
function returns a positive or negative HUGE_VAL.
The code below shows how the wcstod
function works in C:
#include <stdio.h>#include <wchar.h>int main() {// initilaizing stringswchar_t str[] = L"2021.2Educative22";wchar_t* str_end;double result;// converting string to doubleresult = wcstod(str, &str_end);// output resultsprintf("The converted double is %f.\n", result);printf("The remaining string is \'%ls\'.", str_end);return 0;}
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 wcstod
function in Line 12 proceeds to convert the given wide string, “2021.2Educative22”, to a double
.
Since the first characters (“2021.2”) represent a valid floating-point number, the conversion is successful, and the wcstod
function returns the value . The remaining string, “Educative22”, is stored at the location pointed to by str_end
.
Free Resources