C++:从文件中读取 alt 键符号

C++: Reading alt-key symbols from file

本文关键字:alt 符号 读取 文件 C++      更新时间:2023-10-16

我正在尝试从一个Unicode UTF-8文件中读取Alt键符号,然后写入另一个文件。

输入文件如下所示>

��

输出文件如下所示>

239 187 191 225 187 138 225 187 139 225 187 140 225 187

141 225 187 164 225 187 165 225 185 132 225 185 133(每 3 位数字组合后用""代替")

法典:

#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <Windows.h>

///convert as ANSI - display as Unicode
std::wstring test1(const char* filenamein)
{
    std::wifstream fs(filenamein);
    if(!fs.good()) 
    { 
        std::cout << "cannot open input file [" << filenamein << "]n" << std::endl;  
        return NULL; 
    }
    wchar_t c; 
    std::wstring s;
    while(fs.get(c)) 
    { 
        s.push_back(c); 
        std::cout << '.' << std::flush; 
    }
    return s;
}
int printToFile(const char* filenameout, std::wstring line)
{
    std::wofstream fs;
    fs.open(filenameout);
    if(!fs.is_open())
        return -1;
    for(unsigned i = 0; i < line.length(); i++)
    {
        if(line[i] <= 126)  //if its standard letter just print to file
            fs << (char)line[i];
        else  //otherwise do this.
        {
            std::wstring write = L"";
            std::wostringstream ss;
            ss << (int)line[i];
            write = ss.str();
            fs << write;
            fs << std::endl;
        }
    }
    fs << std::endl;

    //2nd test, also fails
    char const *special_character[] = { "u2780", "u2781", "u2782",
  "u2783", "u2784", "u2785", "u2786", "u2787", "u2788", "u2789" };
    //prints out four '?'
    fs << special_character[0] << std::endl;
    fs << special_character[1] << std::endl;
    fs << special_character[2] << std::endl;
    fs << special_character[3] << std::endl;
    fs.close();
    return 1;
}
int main(int argc, char* argv[])
{
    std::wstring line = test1(argv[1]);
    if(printToFile(argv[2], line) == 1)
        std::cout << "Writing success!" << std::endl;
    else std::cout << "Writing failed!" << std::endl;

    return 0;
}

我所期望的是类似于此表中的值:

http://tools.oratory.com/altcodes.html

好的,根据您的代码和注释,我了解以下内容:

  • 您有一个包含 UTF-8 编码字符串的输入文件
  • 您正在Windows上将其读取为宽字符,但没有灌输任何区域设置

所以这是实际发生的事情:

您的代码一次正确读取一个字节的文件,作为 ANSI 文件(就像它是 win1252 编码的一样)。然后,程序将显示所有字节的代码值。我可以确认您在帖子中显示的字节列表是 utf-8 编码字符串ỊịỌọỤụṄṅ,除了记事本++在开头添加了一个字节顺序标记(U + FEFF),这通常不会在UTF8文件中使用 - BOM是3个字节239 187 191(十进制)或0xef 0xbb 0xbf(十六进制)

那你能做什么呢?

一个简单的解决方案(当你使用Windows时)是要求记事本++将文件编码为UTF16LE这是Windows中的本机Unicode格式。这样你就可以实际读取 unicode 字符。

另一种方法是指示您的代码将文件处理为 UTF8。这在Linux上是微不足道的,但在Windows上可能很棘手,因为UTF8自VC2010以来才正确处理。SO的另一篇文章展示了如何在C++流中注入UTF8语言环境。

很抱歉没有提供代码,但我只有一个不支持 UTF8 流的旧 VC2008...我讨厌提供未经测试的代码。