簡體   English   中英

如何使Unicode iostream i / o在Windows和Unix上都可以工作?

[英]How can I make Unicode iostream i/o work in both Windows and Unix-land?

注意:這是一個問題的答案 ,以便記錄其他人可能覺得有用的技術,以便可能意識到其他人更好的解決方案。 請隨意添加批評或問題作為評論。 也可以隨意添加其他答案。 :)


問題#1:

  • 通過流的 Unicode控制台支持在Windows API級別受到嚴格限制。 普通桌面應用程序唯一可用的相關代碼頁是65001,UTF-8。 然后交互式輸入在API級別失敗,甚至非ASCII字符的輸出也失敗 - 並且C ++標准庫實現不提供此問題的解決方法。
#include <iostream>
#include <string>
using namespace std;

auto main() -> int
{
    wstring username;
    wcout << L"Hi, what’s your name? ";
    getline( wcin, username );
    wcout << "Pleased to meet you, " << username << "!\n";
}
H:\personal\web\blog alf on programming at wordpress\002\code>
Active code page: 65001

H:\personal\web\blog alf on programming at wordpress\002\code>

H:\personal\web\blog alf on programming at wordpress\002\code>
Hi, what
                             
H:\personal\web\blog alf on programming at wordpress\002\code>_

在Windows API級別,解決方案是在相關標准流綁定到控制台時使用非基於流的直接控制台i / o 例如,使用WriteConsole API函數。 作為Visual C ++和MinGW g ++標准庫支持的擴展,可以為使用WriteConsole的標准寬流設置模式,並且還有一種模式用於轉換為UTF-8或從UTF-8轉換為外部編碼。

在Unix-land中,對setlocale( LC_ALL, "" )或其更高級別C ++等效的單個調用足以使寬流工作。

但是如何透明地自動設置這些模式,以便使用寬流的相同普通標准C ++代碼在Windows和Unix-land中都可以工作?

注意到,對於那些在Unix-land程序中使用寬文本的想法不寒而栗的讀者來說,這實際上是在Unix-land中使用UTF-8窄文本控制台i / o的可移植代碼的先決條件 也就是說,在Windows中自動使用Unix-land和寬文本中的UTF-8窄文本的代碼變得可能,並且可以建立在W​​indows中對Unicode的支持之上。 但是沒有這樣的支持,一般情況下都沒有可移植性。


問題#2:

  • 使用寬流,輸出項到wchar_t const*默認轉換不起作用。
#include <iostream>
using namespace std;

struct Byte_string
{ operator char const* () const { return "Hurray, it works!"; } };

struct Wide_string
{ operator wchar_t const* () const { return L"Hurray, it works!"; } };

auto main() -> int
{
    wcout << "Byte string pointer: " << Byte_string() << endl;
    wcout << "Wide string pointer: " << Wide_string() << endl;
}
Byte string pointer: Hurray, it works!
Wide string pointer: 0x4ad018

這是我很久以前報告的標准中實現級別的不一致類型的缺陷。 我不確定狀態,它可能已被遺忘(我從來沒有收到任何關於它的郵件),或者可能會在C ++ 17中應用修復程序。 無論如何,如何解決這個問題?


簡而言之,如何制作使用Unicode寬文本控制台i / o的標准C ++代碼,在Windows和Unix-land中工作和實用?

修復了轉換問題:

 #pragma once //---------------------------------------------------------------------------------------- // PROBLEM DESCRIPTION. // // Output of wchar_t const* is only supported via an operator<< template. User-defined // conversions are not considered for template matching. This results in actual argument // with user conversion to wchar_t const*, for a wide stream, being presented as the // pointer value instead of the string. #include <iostream> #ifndef CPPX_NO_IOSTREAM_CONVERSION_FIX namespace std{ template< class Char_traits > inline auto operator<<( basic_ostream<wchar_t, Char_traits>& stream, wchar_t const ch ) -> basic_ostream<wchar_t, Char_traits>& { return operator<< <wchar_t, Char_traits>( stream, ch ); } template< class Char_traits > inline auto operator<<( basic_ostream<wchar_t, Char_traits>& stream, wchar_t const* const s ) -> basic_ostream<wchar_t, Char_traits>& { return operator<< <wchar_t, Char_traits>( stream, s ); } } // namespace std #endif 

在Windows中設置直接i / o模式:

這是Visual C ++和MinGW g ++支持的標准庫擴展。

首先,只是因為它的代碼中使用的定義Ptr類型構建(庫提供的類型建設者的主要缺點是普通型的推理不踢,即它在某些情況下必須仍然使用原運營商的符號):

 ⋮ template< class T > using Ptr = T*; ⋮ 

幫助器定義,因為它在多個文件中使用:

#pragma once
// UTF-8 mode for a stream in Windows.
#ifndef _WIN32
#   error This is a Windows only implementation.
#endif

#include <cppx/stdlib/Iostream_mode.hpp>

#include <stdio.h>      // FILE, stdin, stdout, stderr, etc.

// Non-standard headers, which are de facto standard in Windows:
#include <io.h>         // _setmode, _isatty, _fileno etc.
#include <fcntl.h>      // _O_WTEXT etc.

namespace cppx {

    inline
    auto set_utf8_mode( const Ptr< FILE > f )
        -> Iostream_mode
    {
        const int file_number = _fileno( f );       // See docs for error handling.
        if( file_number == -1 ) { return Iostream_mode::unknown; }
        const int new_mode = (_isatty( file_number )? _O_WTEXT : _O_U8TEXT);
        const int previous_mode = _setmode( file_number, new_mode );
        return (0?Iostream_mode()
            : previous_mode == -1?      Iostream_mode::unknown
            : new_mode == _O_WTEXT?     Iostream_mode::direct_io
            :                           Iostream_mode::utf_8
            );
    }

}  // namespace cppx

模式設定器(基本功能):

#pragma once
// UTF-8 mode for a stream. For Unix-land this is a no-op & the locale must be UTF-8.

#include <cppx/core_language/type_builders.hpp>     // cppx::Ptr
#include <cppx/stdlib/Iostream_mode.hpp>

namespace cppx {
    inline
    auto set_utf8_mode( const Ptr< FILE > ) -> Iostream_mode;
}  // namespace cppx

#ifdef _WIN32   // This also covers 64-bit Windows.
#   include "impl/utf8_mode.for_windows.hpp"    // Using Windows-specific _setmode.
#else
#   include "impl/utf8_mode.generic.hpp"        // A do-nothing implementation.
#endif
 #pragma once #include <stdio.h> // FILE, stdin, stdout, stderr, etc. #include <cppx/core_language/type_builders.hpp> // cppx::Ptr namespace cppx { inline auto set_utf8_mode( const Ptr< FILE > ) -> Iostream_mode { return Iostream_mode::unknown; } } // namespace cppx 
 #pragma once // UTF-8 mode for a stream. For Unix-land this is a no-op & the locale must be UTF-8. #include <cppx/core_language/type_builders.hpp> // cppx::Ptr #include <cppx/stdlib/Iostream_mode.hpp> namespace cppx { inline auto set_utf8_mode( const Ptr< FILE > ) -> Iostream_mode; } // namespace cppx #ifdef _WIN32 // This also covers 64-bit Windows. # include "impl/utf8_mode.for_windows.hpp" // Using Windows-specific _setmode. #else # include "impl/utf8_mode.generic.hpp" // A do-nothing implementation. #endif 

配置標准流。

除了在Windows中適當地設置直接控制台I / O模式或UTF-8之外,這還修復了隱式轉換缺陷; (間接)調用setlocale以便寬流在Unix-land中工作; 設置boolalpha只是為了更好的衡量,作為一個更合理的默認; 並包含與iostreams相關的所有標准庫頭文件(我沒有顯示那樣做的單獨頭文件,並且在某種程度上個人偏好包含多少內容或是否完全包含此內容):

 #pragma once // Standard iostreams but configured to work, plus, as utility, with boolalpha set. #include <raw_stdlib/iostreams.hpp> // <iostream>, <sstream>, <fstream> etc. for convenience. #include <cppx/core_language/type_builders.hpp> // cppx::Ptr #include <cppx/stdlib/utf8_mode.hpp> // stdin etc., stdlib::set_utf8_mode #include <locale> // std::locale #include <string> // std::string #include <cppx/stdlib/impl/iostreams_conversion_defect.fix.hpp> // Support arg conv. inline auto operator<< ( std::wostream& stream, const std::string& s ) -> std::wostream& { return (stream << s.c_str()); } // The following code's sole purpose is to automatically initialize the streams. namespace cppx { namespace utf8_iostreams { using std::locale; using std::ostream; using std::cin; using std::cout; using std::cerr; using std::clog; using std::wostream; using std::wcin; using std::wcout; using std::wcerr; using std::wclog; using std::boolalpha; namespace detail { using std::wstreambuf; // Based on "Filtering streambufs" code by James Kanze published at // <url: http://gabisoft.free.fr/articles/fltrsbf1.html>. class Correcting_input_buffer : public wstreambuf { private: wstreambuf* provider_; wchar_t buffer_; protected: auto underflow() -> int_type override { if( gptr() < egptr() ) { return *gptr(); } const int_type result = provider_->sbumpc(); if( result == L'\\n' ) { // Ad hoc workaround for g++ extra newline undesirable behavior: provider_->pubsync(); } if( traits_type::not_eof( result ) ) { buffer_ = result; setg( &buffer_, &buffer_, &buffer_ + 1 ); } return result ; } public: Correcting_input_buffer( wstreambuf* a_provider ) : provider_( a_provider ) {} }; } // namespace detail class Usage { private: static void init_once() { // In Windows there is no UTF-8 encoding spec for the locale, in Unix-land // it's the default. From Microsoft's documentation: "If you provide a code // page like UTF-7 or UTF-8, setlocale will fail, returning NULL". Still // this call is essential for making the wide streams work correctly in // Unix-land. locale::global( locale( "" ) ); // Effects a `setlocale( LC_ALL, "" )`. for( const Ptr<FILE> c_stream : {stdin, stdout, stderr} ) { const auto new_mode = set_utf8_mode( c_stream ); if( c_stream == stdin && new_mode == Iostream_mode::direct_io ) { static detail::Correcting_input_buffer correcting_buffer( wcin.rdbuf() ); wcin.rdbuf( &correcting_buffer ); } } for( const Ptr<ostream> stream_ptr : {&cout, &cerr, &clog} ) { *stream_ptr << boolalpha; } for( const Ptr<wostream> stream_ptr : {&wcout, &wcerr, &wclog} ) { *stream_ptr << boolalpha; } } public: Usage() { static const bool dummy = (init_once(), true); (void) dummy; } }; namespace detail { const Usage usage; } // namespace detail }} // namespace cppx::utf8_iostreams 

問題中的兩個示例程序僅通過包含上述標題而不是<iostream>或除了<iostream>之外的其他標題來修復。 除此之外,它可以在一個單獨的翻譯單元中(隱式轉換缺陷修復除外,如果需要,必須以某種方式包含它的標題)。 或者例如作為構建命令中的強制包含。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM