If you do want to convert then this should work (I couldn't get wcstombs working):
#include <fstream>
#include <string>
#include <windows.h>
int main()
{
std::fstream File("File.txt", std::ios::out);
if (File.is_open())
{
std::wstring str = L"русский консоли";
std::string result = std::string();
result.resize(WideCharToMultiByte(CP_UTF8, 0, str.c_str(), -1, NULL, 0, 0, 0));
char* ptr = &result[0];
WideCharToMultiByte(CP_UTF8, 0, str.c_str(), -1, ptr, result.size(), 0, 0);
File << result;
}
}
Using raw strings (because a comment complained about my use of std::wstring
):
#include <fstream>
#include <windows.h>
int main()
{
std::fstream File("File.txt", std::ios::out);
if (File.is_open())
{
LPCWSTR wstr = L"русский консоли";
LPCSTR result = NULL;
int len = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, NULL, 0, 0, 0);
if (len > 0)
{
result = new char[len + 1];
if (result)
{
int resLen = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, &result[0], len, 0, 0);
if (resLen == len)
{
File.write(result, len);
}
delete[] result;
}
}
}
}