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

标签 c++ linux unicode fstream gedit

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

在输入文件中,我们有几个数字,翻译后会给出一些字符。例如,一开始表示为 226 130 172 的欧元符号看起来就像一个欧元符号。问题是我无法将其输出到文件,但我可以将其输出到控制台。在程序中有一个扩展 fstream 的方法,它允许向控制台输出最多 4 个字节的符号。但是输出文件中什么也没有,我不明白为什么。我的 friend 使用某种方式输出,将正常的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"Test\n";
wofs << temp;
wofs.close();

您可以引用此链接:Outputting 'wchar_t*' to an 'ofstream'

关于c++ - Linux Ubuntu 中的文件内输出 unicode 符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49182150/

相关文章:

c++ - 在 C/C++ 中,在不使用计算 bool 值的情况下使用 bool 运算符短路来控制流程是否安全?

python - 使用 Python 校正日期和时间

java - 如何使用 RandomAccessFile 读取 UTF8 编码的文件?

c# - Interop.Word 不适用于阿拉伯语文本

c++ - 性能:找到 arr 中最大值的索引(允许并列)

c++ - 如何在 Eclipse 中启动 gdb 调试之前运行 linux 脚本

c - name_to_handle_at() 的逻辑

c# - Monodevelop启动时出现异常: TypeInitializationException

objective-c - unicode表示形式叫什么?

c++ - 如何查看 cmake_automoc 正在运行的确切命令?