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

回答編集履歴

3

mbstowcs を使うコードを追加

2021/05/21 04:20

投稿

kazuma-s
kazuma-s

スコア8222

answer CHANGED
@@ -19,4 +19,36 @@
19
19
  }
20
20
  ```
21
21
  **追記**
22
- `= { L'\0' }` で初期化しているから、`txt[i] = L'\0';` の行は不要でした。
22
+ `= { L'\0' }` で初期化しているから、`txt[i] = L'\0';` の行は不要でした。
23
+
24
+ **追記2**
25
+ 文字列を変換したいのに、文字変換の mbrtowc を使うのは面倒です。
26
+ mbstowcs を使えば次のようになります。
27
+ ```C++
28
+ #include <iostream> // wcout, endl
29
+ #include <cstdlib> // mbstowcs
30
+ #include <clocale> // setlocale
31
+ using namespace std;
32
+
33
+ int main()
34
+ {
35
+ setlocale(LC_CTYPE, "");
36
+ const char text[] = "テストtest";
37
+ wchar_t txt[20];
38
+ int n = mbstowcs(txt, text, 20);
39
+ wcout << n << endl;
40
+ for (int i = 0; txt[i]; i++)
41
+ wcout << txt[i] << " " << hex << int(txt[i]) << endl;
42
+ }
43
+ ```
44
+ 実行結果
45
+ ```text
46
+ 7
47
+ テ 30c6
48
+ ス 30b9
49
+ ト 30c8
50
+ t 74
51
+ e 65
52
+ s 73
53
+ t 74
54
+ ```

2

追記

2021/05/21 04:20

投稿

kazuma-s
kazuma-s

スコア8222

answer CHANGED
@@ -17,4 +17,6 @@
17
17
  for (i = 0; txt[i] != L'\0'; i++)
18
18
  std::wcout << txt[i] << std::endl;
19
19
  }
20
- ```
20
+ ```
21
+ **追記**
22
+ `= { L'\0' }` で初期化しているから、`txt[i] = L'\0';` の行は不要でした。

1

コードの修正

2021/05/19 17:42

投稿

kazuma-s
kazuma-s

スコア8222

answer CHANGED
@@ -14,7 +14,7 @@
14
14
  for (i = 0, j = 0; text[j]; i++, j += f)
15
15
  f = mbrtowc(txt + i, text + j, MB_CUR_MAX, nullptr);
16
16
  txt[i] = L'\0';
17
- for (int i = 0; txt[i] != L'\0'; i++)
17
+ for (i = 0; txt[i] != L'\0'; i++)
18
18
  std::wcout << txt[i] << std::endl;
19
19
  }
20
20
  ```