C++ std::to_wstring() Function

Beginner
5 min read
Updated: Nov 2026
3 examples
std::to_wstring

Definition

In C++, std::to_wstring() converts a number to a std::wstring.

Include <string>.

This is a free function from <string> that works with std::string (and sometimes wstring). Member functions like find live on the string object with a dot; helpers like this are called as std::to_wstring(...).

Syntax

Pass a numeric value.

C++
std::wstring w = std::to_wstring(42);
CallWhat it does
std::to_wstring(val)Numeric value to wide string.

Use when the rest of your API speaks wchar_t. For UTF-8 text, prefer std::string + to_string.

Library declarations
C++
wstring to_wstring(int val);
wstring to_wstring(double val);
// ... other numeric overloads

Parameters

ParameterDescription
valueNumeric value.

Return Value

Return ValueDescription
wstringWide decimal representation.

C++ Examples

Example 1 — Basic to_wstring()

Convert an int to wstring.

C++
#include <iostream>
#include <string>

int main() {
    std::wstring w = std::to_wstring(42);
    std::wcout << w << L'\\n';
    return 0;
}

How It Works

  1. to_wstring builds a wide string.
  2. wcout prints it.
  3. Digits appear as 42.

Example 2 — to_wstring Double

Convert a floating value.

C++
#include <iostream>
#include <string>

int main() {
    std::wstring w = std::to_wstring(2.5);
    std::wcout << w << L'\\n';
    return 0;
}

How It Works

  1. Default floating format applies.
  2. Wide string holds the digits.
  3. Trailing zeros may appear.

Example 3 — Wide Length

Check size of the result.

C++
#include <iostream>
#include <string>

int main() {
    std::wstring w = std::to_wstring(100);
    std::cout << w.size() << '\\n';
    return 0;
}

How It Works

  1. Text is three wide characters: 1,0,0.
  2. size() counts them.
  3. Output is 3.

Frequently Asked Questions

Converts numbers to std::wstring.
Element type is wchar_t instead of char.
<string>.
When working with wide-character APIs.
stoi/stol/... also have wstring overloads.

Next: memccpy()

Keep going through the string functions. Copy bytes until a given byte is copied or n bytes are done.

memccpy() tutorial →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

12 people found this page helpful