Open In App

How to Convert wstring to int in C++?

Last Updated : 22 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, std::wstring is a type of string where each character is of a wide character type. These types of strings can be used to store the numerical strings which can then be converted to their corresponding type. In this article, we will see how to convert a wstring to an int in C++.

Input:
wstr = L"12345";

Output:
int num = 12345;

Converting a std::wstring to int in C++

To convert a wstring to an integer in C++, we can use the std::stoi function provided in the <string> library that converts a string to an integer. This function also has an overload that accepts a std::wstring.

Syntax of std::stoi()

stoi(wstr);

Here, wstr is the wstring to be converted to int. This function will return the integer value extracted from the string.

C++ Program to Convert wstring to int

The below program demonstrates how we can convert a string to int using stoi() function in C++.

C++
// C++ program to illustrate how to convert wstring to int
#include <iostream>
#include <string>
using namespace std;

int main()
{
    // Creating wstring
    wstring str = L"12345";

    // Converting wstring to int
    int num = stoi(str);

    // Print the int
    cout << "Number: " << num << endl;

    return 0;
}

Output
Number: 12345

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



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads