質問するログイン新規登録

回答編集履歴

3

close不要

2018/05/24 03:17

投稿

yumetodo
yumetodo

スコア5852

answer CHANGED
@@ -71,7 +71,5 @@
71
71
  std::ofstream ofs("out.txt");
72
72
 
73
73
  ofs << utf_16_to_utf_8(L"あいうえお") << std::endl;
74
-
75
- ofs.close();
76
74
  }
77
75
  ```

2

convert

2018/05/24 03:17

投稿

yumetodo
yumetodo

スコア5852

answer CHANGED
@@ -11,4 +11,67 @@
11
11
  ```
12
12
 
13
13
 
14
- でいけなかったっけか。
14
+ でいけなかったっけか。
15
+
16
+ ---
17
+
18
+ > しかし、固定文字列ではなく
19
+
20
+ あー、そりゃそうだ。失礼、どうも寝ぼけていたようで。
21
+
22
+ > WideCharToMultiByte を使用する方法として、以下の記事を参考にして作成しましたが、16バイト目に無駄なNULL(0x00)が含まれていました。
23
+
24
+ まずUTF-8なbyte列で「ありうえお」を表現すると
25
+
26
+ ```
27
+ E3 81 82 E3 81 84 E3 81 86 E3 81 88 E3 81 8A
28
+ ```
29
+
30
+ のようになります。
31
+
32
+ ここで
33
+
34
+ > out2.txtがテキストエディタを使いUTF-8(BOMなし)で「あいうえお」という文字列を書き込んだファイル。
35
+
36
+ の出力と見比べると
37
+
38
+ ```
39
+ 0D 0A
40
+ ```
41
+
42
+ が余計についている事がわかりますが、これは言うまでもなくCR+LFですね(改行コード)。
43
+
44
+ > out.txtがプログラムで作成したテキストファイル。
45
+
46
+ の出力のこれも``std::endl`からきているものですね。
47
+
48
+ さて、NULL文字が含まれる原因は`wide_to_utf8_winapi`の実装がだめだからです。
49
+
50
+ 修正版がこちらです。
51
+
52
+ ```cpp
53
+ #include <string>
54
+ #include <windows.h>
55
+ #include <fstream>
56
+ #include <system_error>
57
+ std::string utf_16_to_utf_8(const std::wstring& str) {
58
+ static_assert(sizeof(wchar_t) == 2, "this function is windows only");
59
+ const int len = ::WideCharToMultiByte(CP_UTF8, 0, str.c_str(), -1, nullptr, 0, nullptr, nullptr);
60
+ std::string re(len * 2, '\0');
61
+ if (!::WideCharToMultiByte(CP_UTF8, 0, str.c_str(), -1, &re[0], len, nullptr, nullptr)) {
62
+ const auto er = ::GetLastError();
63
+ throw std::system_error(std::error_code(er, std::system_category()), "WideCharToMultiByte:(" + std::to_string(er) + ')');
64
+ }
65
+ const std::size_t real_len = std::char_traits<char>::length(re.c_str());
66
+ re.resize(real_len);
67
+ re.shrink_to_fit();
68
+ return re;
69
+ }
70
+ int main() {
71
+ std::ofstream ofs("out.txt");
72
+
73
+ ofs << utf_16_to_utf_8(L"あいうえお") << std::endl;
74
+
75
+ ofs.close();
76
+ }
77
+ ```

1

fstream

2018/05/24 03:10

投稿

yumetodo
yumetodo

スコア5852

answer CHANGED
@@ -1,11 +1,12 @@
1
1
  普通に
2
2
 
3
3
  ```cpp
4
- #include <iostream>
4
+ #include<fstream>
5
5
 
6
6
  int main()
7
7
  {
8
+ std::ofstream ofs("out.txt");
8
- std::cout << u8"ありきたり" << std::endl;
9
+ ofs << u8"ありきたり" << std::endl;
9
10
  }
10
11
  ```
11
12