打印西班牙语(或意大利语)口音和 ñ

问题描述 投票:0回答:1

当我读取包含特殊字符(例如 á ó ñ ü è)的文件,然后在命令提示符中打印它们时,我遇到了问题。

在下面的示例中,读取的文件中保存了“普通字符 á é í ó ú ñ”,但一个输出是:“普通字符 ├í ├® ├¡ ├│ ├║ ├▒” 另一个:“Ø#”。

#include <iostream>
#include <string>
#include <fstream>
#include <Windows.h>
using namespace std;

int main() {
    
    //setlocale(LC_CTYPE, "Spanish");
        //wofstream file_write;
    
    wifstream file_read;
    
    wstring aux;    
    
    file_read.open("general\\read_file.txt");
    
    
    if(file_read.fail()){
        printf("Fail\n");
    }
    
    else{
        
        getline(file_read, aux);
        
        wcout << aux << endl;
        
        wprintf(L"%ls\n", aux);
        
    }
    
    file_read.close();
    
    
    return 0;
}


如您所见,我尝试使用 wcout、wfstreams、wprintf 和 setLocale 函数,但这些都不起作用,是什么导致了问题?对于上下文,我的操作系统是 windows 11

c++ unicode ascii iostream
1个回答
0
投票

宽流几乎从来都不是 I/O 的好选择,因为它们将输入视为

wchar_t
的序列,而现在文件通常以 UTF-8 存储。因此,发生的情况是一对 UTF-8 代码单元被错误地解释为单个 UTF-16 代码单元。在 C++23 中,您将能够使用
std::print
正确处理 Windows 上的 Unicode。同时,您可以使用
std::print
所基于的 {fmt} 库。例如:

#include <string>
#include <fstream>
#include <fmt/core.h>

int main() {
  std::ifstream file_read("read_file.txt");
  std::string s;
  std::getline(file_read, s);
  fmt::print("{}\n", s);
}

如果您使用 MSVC,您应该使用

/utf-8
进行编译,并且只要您的文件是 UTF-8,您应该会得到正确的输出。

© www.soinside.com 2019 - 2024. All rights reserved.