1
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++がターミナルで文字化けする

Last updated at Posted at 2025-12-01

はじめに

お読みいただきありがとうございます。
VSCodeでC++を使っていると出力した文字が文字化けして困ったので、対処法をメモします。
これ以外にも対応はありそうです。

環境

  • Windows11 Home 25H2
  • gcc (Built by MinGW-Builds project) 15.2.0
  • VSCode 1.105.1
  • Code Runner 0.12.2

内容

VSCodeにC++を書いて、CodeRunnerで実行すると文字化けしたのでこれを解決します。

index.cpp
#include <iostream>
using namespace std;

int main() {
  cout << "こんにちは" << endl;
}
出力
縺薙s縺ォ縺。縺ッ

原因

VSCodeのファイルはShift-JISとして保存するのに、実行するときにWindowsはUTF-8として解釈するから文字化けする。
image.png(←VSCode右下)

対処法

CodeRunnerの設定を変えて、コンパイルするときの文字コードをShift-JISにする。
これでWindowsでもShift-JISとして実行されるから文字化けは起きなくなります。

  1. 拡張機能のCodeRunnnerを開き、歯車マークから設定を開く。
    image.png

  2. 「Code-runner: Executor Map」という項目の「setting.jsonで編集」を押してsetting.jsonを開く。
    image.png

  3. setting.json内で"code-runner.executorMap"の中にある"cpp"という項目を探す。
    検索(Ctrl + F)が便利です。

setting.json
"code-runner.executorMap": {
    "cpp": "cd $dir && g++ $fileName -o $fileNameWithoutExt && $dir$fileNameWithoutExt"
}

これはC++(cpp)を実行するときは右側の

cd $dir && g++ $fileName -o $fileNameWithoutExt && $dir$fileNameWithoutExt

というコマンドでコンパイルして実行するよという意味です。
2つ目の&&の前にShift-JISを表す-fexec-charset=CP932を足して

cd $dir && g++ $fileName -o $fileNameWithoutExt -fexec-charset=CP932 && $dir$fileNameWithoutExt

に書き換えて保存する。
これで文字化けしなくなりました!

設定を元に戻すときの為に元のコードをコメントアウトして、新しいコードを書くといいかも。

コマンドの内容について

シェルコマンドでは前の処理が正常に終了したときに&&でつないだ後ろの処理も実行できます。

cd $dir && g++ $fileName -o $fileNameWithoutExt -fexec-charset=CP932 && $dir$fileNameWithoutExt
cd $dir

現在のディレクトリに移動するみたいなこと

&& g++ {ソースファイル名} -o {実行ファイル名} {文字コード指定} # ソースファイルを実行ファイルにコンパイルする

$fileNameは現在のファイル名を表す。
$fileNameWithoutExtは現在のファイル名から拡張子を除いた名前を表す。
-fexec-charset=CP932は文字コードをCP932(Shift-JISのこと)に指定している。

&& $dir$fileNameWithoutExt

コンパイルしたファイルを実行することを表す。

参考リンク

1
0
1

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
1
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?