0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【C++】UTF-8でコンソール出力を行う方法

Posted at

コンソールでUTF-8の出力を行いたいのに、WindowsのデファクトスタンダードがSJISで設定に戸惑う…ということが、稀にあるかと思います。
本記事では、C++使用時にUTF-8でのコンソール出力の方法をまとめます。

環境

  • VisualStadio2022
  • C++23

設定

本記事ではコンソールでUTF-8を扱うために、u8stringというクラスを使用します。
そのためには言語規格がC++20以降である必要があります。
最新版がよろしいかと思いますので、基本的には現時点での最新版にすることを強く勧めます。
本記事ではC++23への変更を行います。

言語規格の変更方法

画面上部GUIからプロジェクト->プロパティをクリックでプロパティページを開きます。
スクリーンショット (82).png
構成プロパティ->C/C++->言語->C++言語標準の右UIをクリックし、C++23を選択(今回はC++20以降ならOK)
スクリーンショット (83).png
プロパティページの右下の適用をクリックし、変更の適用を行います。
スクリーンショット (84).png

実装

C++では、<windows.h>内のSetConsoleOutputCP()関数を利用することで、コンソールに出力する文字コードを変更することが出来ます。
UTF-8に変更するためのマクロはCP_UTF8です。
文字列型にはstd::u8stringを使用し、出力時にはreinterpret_castで出力できる型(const char*)に変換することで、UTF-8での出力が実現できます。

UTF-8.cpp
#include <iostream>
#include <windows.h>//SetConsoleOutputCP()を使用するために必要
#include <string>

int main() {
	SetConsoleOutputCP(CP_UTF8);//出力コードをUTF-8に設定
	std::u8string s = u8"こんにちは、世界";//UTF-8文字列リテラル
	//出力できる型に変換を行って出力
	std::cout << reinterpret_cast<const char*>(s.c_str()) << std::endl;

	system("pause");
	return 0;
}
result
こんにちは、世界
Press any key to continue . . .

ここで文字化けせずに出力されていたら、UTF-8での出力が成功となります。

総括

  • u8stringを扱うためには、C++の言語規格をC++20以上にする必要がある。
  • <windows.h>内のSetConsoleOutputCP()関数を利用することで、コンソールに表示する文字コードを変更できる。
  • u8stringstd::coutで出力する際には、reinterpret_castで出力できる型(const char*)に変換する必要がある。
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?