The Windows API seems big on UNICODE
, you make a new project in Visual C++ and it sets it to UNICODE
by default.
And me trying to be a good Windows programmer, I want to use UNICODE
.
The problem is the C++ Standard Library and STL (such as std::string, or std::runtime_error) don't work well with UNICODE
strings.
I can only pass a std::string, or a char*
to std::runtime_error, and i'm pretty sure std::string doesn't support UNICODE
.
So my question is, how should I use things such as std::runtime_error? Should I mix UNICODE
and regular ANSI
? (I think this is a bad idea...)
Just use ANSI
in my whole project? (prefer not..) Or what?
In general you shouldn’t mix those two encodings. However, exception messages are something that is only of interest to the developer (e.g. in log files) and should never be shown to the user (but look at Jim’s comment for an important caveat).
So you are on the safe side if you use UNICODE
for your whole user-faced interface and still use std::exception
etc. behind the scenes for developer messages. There should be no need ever to convert between the two.
Furthermore, it’s a good trick to define a typedef
for UNICODE
-independent strings in C++:
typedef std::basic_string<TCHAR> tstring;
… and analogously define tcout
, tcin
etc. conditionally:
#ifdef UNICODE
std::wostream& tcout = std::wcout;
std::wostream& tcerr = std::wcerr;
std::wostream& tclog = std::wclog;
std::wistream& tcin = std::wcin;
#else
std::ostream& tcout = std::cout;
std::ostream& tcerr = std::cerr;
std::ostream& tclog = std::clog;
std::istream& tcin = std::cin;
#endif
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With