iT邦幫忙

6

[VSCode] Visual Studio Code 執行 C++ (5) - 中文亂碼

發現程式使用 printf 輸出命令視窗時中文會出現亂碼。
http://ithelp.ithome.com.tw/upload/images/20171004/20106865PJS9Wz2fi4.jpg

Google 後發現因為 Windows 命令視窗中文預設使用 Big5 編碼,但 VSCode 預設使用 UTF8 編碼,所以輸出後的結果才會出現亂碼。
http://ithelp.ithome.com.tw/upload/images/20171004/201068651shAx8dvv7.jpg

要解決這個問題有兩種方法,第一種可以將命令視窗中文預設編碼改為 UTF8 ,第二種將 VSCode 預設編碼改為 Big5 ,這裡我採用第二種做法。
http://ithelp.ithome.com.tw/upload/images/20171003/20106865tdFDYpO5J9.jpg
在左下角開啟 VSCode 設定檔,加入以下內容。

"files.encoding": "cp950"

設定完後,我開啟一個新的檔案,然後重新打上程式,執行,結果正常沒有亂碼。
http://ithelp.ithome.com.tw/upload/images/20171004/20106865R6s37xnYNt.jpg

不過開啟舊的檔案發現程式內中文的地方變成亂碼。
http://ithelp.ithome.com.tw/upload/images/20171004/20106865b3bss6qoVX.jpg
這是因為舊的檔案還是用 UTF8 編碼,但 VSCode 卻用 Big5 解碼,所以變成程式出現亂碼,要解決這個問題只需要將舊檔案另存成 Big5 編碼即可。

http://ithelp.ithome.com.tw/upload/images/20171004/20106865XfJBQoGZgM.jpg
選取右下角編碼。
http://ithelp.ithome.com.tw/upload/images/20171004/20106865FymU8hZLzZ.jpg
選以編碼重新開啟。
http://ithelp.ithome.com.tw/upload/images/20171004/2010686570jYsBYTwI.jpg
UTF-8,然後再點一次右下角編碼。
http://ithelp.ithome.com.tw/upload/images/20171004/20106865ZJZW60yvHP.jpg
選以編碼儲存。
http://ithelp.ithome.com.tw/upload/images/20171004/20106865U4Cg5JiFNX.jpg
Traditional Chinese (Big5)
http://ithelp.ithome.com.tw/upload/images/20171004/20106865u4qn6BsCCf.jpg
可以看到舊檔案的編碼已經從 UTF8 轉成 Big5,執行結果也正確。

結語:
因為在 VSCode files.encoding 是全域設定,所以如果有在開發其他程式,例如網頁就會受到影響,因為 html 通常使用 UTF8 編碼,這裡我還沒有想到更好的解法,如果大家有經驗歡迎分享 XD。

相關文章:
[VSCode] Visual Studio Code 執行 C++ (1) - 安裝 VSCode + MinGW
[VSCode] Visual Studio Code 執行 C++ (2) - IntelliSense + Building + Debugging
[VSCode] Visual Studio Code 執行 C++ (3) - 語法檢查
[VSCode] Visual Studio Code 執行 C++ (4) - 範本 (Template)
[VSCode] Visual Studio Code 執行 C++ (5) - 中文亂碼
[VSCode] Visual Studio Code 執行 C++ (6) - Code Runner


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 則留言

1
海綿寶寶
iT邦大神 1 級 ‧ 2017-10-05 10:44:07

在您繼續寫下去的同時
我想提供您一項資訊
就是本站每年都會舉行的「鐵人賽」
有空時不妨逛一下看看
2017鐵人賽

只有這五篇,哈哈
也是看到各位大大的鐵人賽文章,才會想要在這裡分享心得 :D

只有五篇,那我按個讚好了
/images/emoticon/emoticon12.gif

哈哈,感謝~

0
shiaobin
iT邦新手 4 級 ‧ 2022-12-21 17:41:15

可以設定讓 Visual Studio Code 自動猜測編碼。
"files.autoGuessEncoding": true

謝謝!

我要留言

立即登入留言