質問
C++17でUTF-8(BOMなし)のファイルを出力したいです。
試したこと1
このプログラムの場合0バイトのout.txtが作成されました。
cpp
1#include <iostream> 2#include <string> 3#include <fstream> 4 5int main() { 6 std::wofstream ofs("out.txt"); 7 ofs << L"あいうえお" << std::endl; 8 ofs.close(); 9}
試したこと2
このプログラムで問題なく出力できましたが警告が出ています。警告をなくしたいです。
また、#define _SILENCE_CXX17_CODECVT_HEADER_DEPRECATION_WARNING
または
#define _SILENCE_ALL_CXX17_DEPRECATION_WARNINGS
すると警告は出ませんができれば他の方法で解決したいです。
cpp
1#include <iostream> 2#include <vector> 3#include <string> 4#include <fstream> 5#include <codecvt> 6 7int main() { 8 std::wofstream ofs("out.txt"); 9 // C4996 warning STL4017 10 ofs.imbue(std::locale(std::locale(), new std::codecvt_utf8<wchar_t>)); 11 12 ofs << L"あいうえお" << std::endl; 13 14 ofs.close(); 15}
試したこと3
WideCharToMultiByte を使用する方法として、以下の記事を参考にして作成しましたが、16バイト目に無駄なNULL(0x00
)が含まれていました。
http://nekko1119.hatenablog.com/entry/2017/01/02/054629
※out.txtがプログラムで作成したテキストファイル。out2.txtがテキストエディタを使いUTF-8(BOMなし)で「あいうえお」という文字列を書き込んだファイル。
cpp
1#include <Windows.h> 2 3#include <iostream> 4#include <vector> 5#include <string> 6#include <fstream> 7 8std::string wide_to_utf8_winapi(std::wstring const& src) 9{ 10 auto const dest_size = ::WideCharToMultiByte(CP_UTF8, 0U, src.data(), -1, nullptr, 0, nullptr, nullptr); 11 std::vector<char> dest(dest_size, '\0'); 12 if (::WideCharToMultiByte(CP_UTF8, 0U, src.data(), -1, dest.data(), dest.size(), nullptr, nullptr) == 0) { 13 throw std::system_error{ static_cast<int>(::GetLastError()), std::system_category() }; 14 } 15 return std::string(dest.begin(), dest.end()); 16} 17 18int main() { 19 std::ofstream ofs("out.txt"); 20 21 ofs << wide_to_utf8_winapi(L"あいうえお") << std::endl; 22 23 ofs.close(); 24}
環境
OS | Windows 10 64bit 1709 |
IDE | Visual Studio 2017 |
Windows SDK Version | 10.0.17134.0 |
文字セット | Unicode 文字セットを使用する |
PlatformToolSet | Visual Studio 2017 (v141) |
C++言語標準 | ISO C++17 Standard (/std:c++17) |
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
退会済みユーザー
2018/05/24 02:47
退会済みユーザー
2018/05/24 04:14