wcout用于不同的语言环境 [英] wcout for different locales

查看:109
本文介绍了wcout用于不同的语言环境的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以前曾经为Windows编写代码,现在试图使代码在Linux上工作.这是一个示例代码,我想问一个问题:

#include< iostream>

int main(int argc,char * argv []){
setlocale(LC_ALL,"be_BY.utf8");
const char * HelloWorld_char =Вітаю,шаноўныспадар!";
const wchar_t * HelloWorld_wchar_t = LВітаю,шаноўныспадар!";
std :: cout<< HelloWorld_char<< std :: endl;
std :: wcout<< HelloWorld_wchar_t<< std :: endl;
返回0;
}

源文件是UTF-8编码的.我用
编译
g ++ -fexec-charset = utf-8 -fwide-exec-charset = utf-8 test.cpp

使用cout的代码行有效(无论我用setlocale!?设置了什么语言环境).但是wcout会打印垃圾.你能解释为什么吗?是否可以对wcout进行本地化?谢谢

PS.好吧,这些字符串在我的页面上看起来不太好,但它们只包含"Hello,World!".

I used to code for Windows now I''m trying to make the code work for Linux. This is a sample code that I''d like to ask a question about:

#include <iostream>

int main (int argc, char * argv []) {
setlocale (LC_ALL, "be_BY.utf8");
const char * HelloWorld_char = "Вітаю, шаноўны спадар!";
const wchar_t * HelloWorld_wchar_t = L"Вітаю, шаноўны спадар!";
std::cout << HelloWorld_char << std::endl;
std::wcout << HelloWorld_wchar_t << std::endl;
return 0;
}

The source file is UTF-8 encoded. I compile it with

g++ -fexec-charset=utf-8 -fwide-exec-charset=utf-8 test.cpp

The line of code with cout works (no matter what locale I set with setlocale !?). But wcout prints rubbish. Can you explain why? Is it possible to localize wcout as well? Thanks

PS. Well, the strings don''t look nice on my page but they just contain "Hello, World!" text in Belarusian.

推荐答案

有两个不同的方面应该合作.

1.编写源代码的方式:确保您的编辑器使用UTF-8编码而不是SBCS或MBCS代码页保存CPP文件,否则编译器将按您期望的方式看到文字字符串.

2. cout wcout 使用C ++全局std:locale构面执行其任务.它们不一定与C语言环境同步.
正确的方法是实例化C ++本地类,并将其注入流中,例如

There are two distinct things that should cooperate.

1. The way the source code is written: make shure your editor saved the CPP files with UTF-8 encoding and not as an SBCS or MBCS codepage, otherwise the compiler sees the literal strings differently on what you expect.

2. cout and wcout use the C++ global std:locale facets to perform their task. They are not necessarily synchronized with the C locales.
The proper way is instantiate a C++ local class, and imbue it in the streams, like

#include <locale>
#include <iostreams>
int main()
{
    std::locale loc("be_BY.utf8");
    std::cout.imbue(loc);
    std::wcout.imbue(loc);

    //Your writings goes here, remove the setlocale call
}



[



This[^] may also be helpful.


我的问题是相同的,我使用的是Fedora 13 x86_64.是错误还是在使用"setlocale"时我们在配置中进行了修改?
My problem is the same, I use Fedora 13 x86_64. Is it a bug or when we used "setlocale" we modified something in our configs?


这篇关于wcout用于不同的语言环境的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆