2016-08-20 48 views
2

我想在我的std::strings中存儲utf8個字符。爲此,我使用boost::locale轉換例程。正確使用boost locale生成器

在我的第一個測試一切正常:

#include <boost/locale.hpp> 

std::string utf8_string = boost::locale::conv::to_utf<char>("Grüssen", "ISO-8859-15"); 
std::string normal_string = boost::locale::conv::from_utf(utf8_string, "ISO-8859-15"); 

預期的結果是:

utf8_string = "Grüssen" 
normal_string = "Grüssen" 

爲了擺脫通過「ISO-8859-15」作爲字符串我試圖用代替std::locale。但不出所料

// Create system default locale 
boost::locale::generator gen; 
std::locale loc=gen("ISO8859-15"); 
std::locale::global(loc); 
// This is needed to prevent C library to 
// convert strings to narrow 
// instead of C++ on some platforms 
std::ios_base::sync_with_stdio(false); 

std::string utf8_string = boost::locale::conv::to_utf<char>("Grüssen", std::locale()); 
std::string normal_string = boost::locale::conv::from_utf(utf8_string, std::locale()); 

結果並不:

utf8_string = "Gr|ssen" 
normal_string = "Gr|ssen" 

這有什麼錯我的使用使用std::locale和發電機的? (編譯器VC2015,多字節字符集)

+0

你如何檢查結果? 「期望」utf8_string =「Grüssen」'這很奇怪,因爲你基本上「期望」錯誤的解碼。另外,什麼是源文件編碼?如果它不是latin1,那就錯了。 – sehe

+0

我用VC2015 Debugger檢查過它,我用win32 TextOutA打印normal_string,它是從utf8轉換而來的。 Notepad ++告訴我文件編碼是ANSI。那麼,看看utf_8字符串Grüssen「是不是被磨損的,因爲」Grâsse「是utf8編碼的Grüsse當你用期待iso8859-1的東西渲染時的樣子。那麼std :: locale在這裏使用有什麼問題,爲什麼第二個版本可以工作? –

回答

1

boost::locale::generator想要一個區域ID,不僅是一個編碼(相同的編碼可通過多個語言環境中使用)。它使用的方案是language_country.encoding,所以你需要de_DE.ISO-8859-15

此外,您通過在源代碼中添加非ASCII字符來玩火。小心。

您對sync_with_stdio()的評論也很奇怪。它只是確保緩衝區被刷新。

+0

'sync_with_stdio()'確保在C/C++ IO **和**之間緩衝區不會/不必要地被刷新,並且刪除了線程同步的要求http://en.cppreference.com/w/ CPP/IO /的ios_base/sync_with_stdio – sehe