Linux Ubuntu 中的文件内输出 unicode 符号

In-file output unicode symbols in Linux Ubuntu

本文关键字:输出 unicode 符号 文件 Ubuntu Linux      更新时间:2023-10-16

我写了一个从十进制数到Unicode字符的翻译器。

在输入文件中,我们有几个数字,翻译后会给出一些字符。例如,欧元符号(开头表示为 226 130 172(看起来与欧元符号完全一样。问题是我无法将其输出到文件,但可以将其输出到控制台。在程序中有一种扩展 fstream 的方法,它允许将最多 4 个字节的符号输出到控制台。但是输出文件中没有任何内容,我不明白为什么。我的朋友使用某种方式输出,将正常的 cout 流重定向到文件,但是,据我了解,此方法仅适用于 Windows。我使用 Ubuntu 16.04,这种方法对我不起作用。我尝试将 gedit(Ubuntu 中的标准文本编辑器(配置为显示,但没有成功。在此代码中,我首先打开扩展流,然后执行以下代码。

int input, result = 0;
if(!fin.is_open()){
    cout << "Не удалось открыть файл!" << endl;
}
else{
    while(fin >> input){
        if(input >= 240){
            input -= 240;
            result += input << 18;
            fin >> input;
            input -= 128;
            result += input << 12;
            fin >> input;
            input -= 128;
            result += input << 6;
            fin >> input;
            input -= 128;
            result += input;
            wcout << (wchar_t)result << endl;
            fout << (wchar_t)result;
        }
        else if(input >= 224){
            input -= 224;
            result += input << 12;
            fin >> input;
            input -= 128;
            result += input << 6;
            fin >> input;
            input -= 128;
            result += input;
            wcout << (wchar_t)result << endl;
            fout << (wchar_t)result;
        }
        else if(input >= 192){
            input -= 192;
            result += input << 6;
            fin >> input;
            input -= 128;
            result = input;
            wcout << (wchar_t)result << endl;
            fout << (wchar_t)result;
        }
        else{
            wcout << (wchar_t)input << endl;  
            fout << (wchar_t)input;
        }
    }
}
  fin.close();
  fout.close();
  return 0;
}

您必须将 fout 声明为 std::wofstream 而不是 std::ofstream 才能将 wchar 输出到文件中。例:

wchar_t *temp = L"wchar";
std::wofstream wofs;
wofs.open("output.txt", std::ios::out);
wofs << L"Testn";
wofs << temp;
wofs.close();

您可以参考此链接:将"wchar_t*"输出到"流">