我在用C++编写法语字符到控制台时遇到了问题。该字符串使用std::ifstream和std::getline从文件中加载,然后使用std::cout打印到控制台。以下是文件中字符串的内容:
La cha ne qui对应的语码为"TEST_CODE“n'a pasététrouvéeàl‘助手locale "fr”。
下面是字符串的打印方式:
La cha ne qui对应的语码为"TEST_CODE“n‘au t trouv e l’‘aide locale "fr”。
我怎样才能解决这个问题?
发布于 2012-11-15 03:55:52
问题是控制台使用的代码页与系统的其他部分不同。例如,通常为美洲和西欧设置的Windows系统使用CP1252,但这些地区的控制台使用CP437或CP850。
您可以设置控制台输出代码页以匹配正在使用的编码,也可以转换字符串以匹配控制台的输出代码页。
设置控制台输出代码页:
SetConsoleOutputCP(GetACP()); // GetACP() returns the system codepage.
std::cout << "La chaîne qui correspond au code \"TEST_CODE\" n'a pas été trouvée à l'aide locale \"fr\".";或多种编码之间转换的方法之一(此方法需要VS2010或更高版本):
#include <codecvt> // for wstring_convert
#include <locale> // for codecvt_byname
#include <iostream>
int main() {
typedef std::codecvt_byname<wchar_t,char,std::mbstate_t> codecvt;
// the following relies on non-standard behavior, codecvt destructors are supposed to be protected and unusable here, but VC++ doesn't complain.
std::wstring_convert<codecvt> cp1252(new codecvt(".1252"));
std::wstring_convert<codecvt> cp850(new codecvt(".850"));
std::cout << cp850.to_bytes(cp1252.from_bytes("...été trouvée à...\n")).c_str();
}后一个例子假设您实际上需要在1252到850之间进行转换。您可能应该使用函数GetOEMCP()来计算实际的目标代码页,源代码页实际上取决于您对源代码使用了什么,而不是取决于运行程序的机器上的GetACP()的结果。
还请注意,该程序依赖于一些标准没有保证的内容: wchar_t编码在地区间共享。这在大多数平台上都是正确的--通常在所有语言环境中,wchar_t都使用某些Unicode编码--但并不是全部。
理想情况下,您可以在任何地方使用UTF-8,下面的功能会很好,就像现在在其他平台上一样:
#include <iostream>
int main() {
std::cout << "La chaîne qui correspond au code \"TEST_CODE\" n'a pas été trouvée à l'aide locale \"fr\".\n";
}不幸的是,Windows不能以这种方式支持UTF-8,而不放弃UTF-16作为wchar_t编码并采用4字节wchar_t,或者违反标准和标准一致性程序的要求。
发布于 2012-11-15 08:03:56
如果要在控制台中写入Unicode字符,则必须执行一些initialization操作。
_setmode(_fileno(stdout), _O_U16TEXT);然后正确显示您的法语字符(我使用Consolas作为控制台字体进行了测试):
#include <fcntl.h>
#include <io.h>
#include <iostream>
#include <ostream>
#include <string>
using namespace std;
int main()
{
// Prepare console output in Unicode
_setmode(_fileno(stdout), _O_U16TEXT);
//
// Build Unicode UTF-16 string with French characters
//
// 0x00EE - LATIN SMALL LETTER I WITH CIRCUMFLEX
// 0x00E9 - LATIN SMALL LETTER E WITH ACUTE
// 0x00E0 - LATIN SMALL LETTER A WITH GRAVE
wstring str(L"La cha");
str += L'\x00EE';
str += L"ne qui correspond au code \"TEST_CODE\" ";
str += L"n'a pas ";
str += L'\x00E9';
str += L't';
str += L'\x00E9';
str += L" trouv";
str += L'\x00E9';
str += L"e ";
str += L'\x00E0';
str += L" l'aide locale \"fr\".";
// Print the string to the console
wcout << str << endl;
}请考虑阅读Michael的以下博客文章:
此外,如果您正在读取文件中的一些文本,您必须知道使用哪个编码:UTF-8?16LE?16BE?一些特定的代码页?然后,您可以从特定的编码转换为Unicode UTF-16,并在Windows应用程序中使用UTF-16。若要从某些代码页(或从UTF-8)转换为UTF-16,可以使用API接口或CA2W。
https://stackoverflow.com/questions/13391252
复制相似问题