Open In App

How to Convert wstring to double in C++

Last Updated : 27 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In C++, std::wstring is a type of string where each character is of a wide character type. Converting wstring to a double in C++ can be a common requirement especially when dealing with the inputs that are stored as unicode characters. In this article, we will learn how to convert a wstring to a double in C++.

Example

Input:
wstring input = L"3.14159"

Output:
Converted double value is: 3.14159

Converting wstring to double in C++

To convert a wstring also known as wide string to a double in C++, we can use the std::stod() function provided by the C++ STL library. This function takes a string or wstring as input and returns the corresponding double value.

Syntax to Use std::stod

stod(wstring(str.begin(),str.end()));

Here,

  • str denotes the name of the input wide string.
  • str.begin() is an iterator pointing to the first character of the given wide string.
  • str.end() is an iterator pointing to the end of the given wide string.

C++ program to Convert a wstring to double

The following program illustrates how we can convert a wstring to a double value in C++.

C++
// C++ program to Convert a wstring to double

#include <iostream>
#include <string>
using namespace std;

int main()
{
    // Declare the wide string
    wstring input = L"3.15159";

    // Convert wide string to double using stod
    double result
        = stod(wstring(input.begin(), input.end()));

    // Print the converted double value
    cout << "Converted double value: " << result << endl;

    // Print the type of result using typeid
    cout << "Type of result: " << typeid(result).name()
         << endl;

    return 0;
}


Output

Converted double value: 3.15159
Type of result: d

Time Complexity: O(N), here N is the length of the wide string.
Auxiliary Space: O(1)


Next Article
Practice Tags :

Similar Reads