C++:从文件中读取 alt 键符号
C++: Reading alt-key symbols from file
我正在尝试从一个Unicode UTF-8文件中读取Alt键符号,然后写入另一个文件。
输入文件如下所示>
嘻
��
输出文件如下所示>
239 187 191 225 187 138 225 187 139 225 187 140 225 187141 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...我讨厌提供未经测试的代码。
相关文章:
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 有符号的int和int-有没有一种方法可以在C++中区分它们
- 将无符号char*转换为std::istream*C++
- 如何在C++中将一个无符号的 int 转换为两个无符号的短裤?
- vscode g++链路故障:体系结构x86_64的未定义符号
- 从矢量<无符号字符>转换为字符* 包括垃圾数据
- 如何理解将半精度指针转换为无符号长指针和相关的内存对齐
- Visual studio代码重构似乎不起作用(例如,重命名符号-f2)
- 使用gcc从静态链接的文件中查找可选符号
- C++中无符号字符溢出
- 使用无符号字符数组有效存储内存
- C++:Application.cpp中抛出了未解析的外部符号(解决方案在问题的末尾,供未来的读者参考)
- VC++本机单元测试,找不到调试符号
- 为什么我必须在C++中添加一个赋值符号来声明一个数组
- 检查TCHAR数组输入是否为带符号整数C++
- 用符号版本替换对函数的所有调用
- 未解析的外部符号_MsiLocateComponentW@12.
- 如何打印boost多精度128位无符号整数
- C++模板函数,用于比较任何无符号整数和有符号整数
- C++:从文件中读取 alt 键符号