c++unicodewofstream

C++ std::wofstream unicode issue.


I wrote this code using VS 2012:

std::wofstream logout("my_log.txt", std::ios_base::out | std::ios_base::trunc);
std::locale utf8_locale(locale(), new codecvt_utf8<wchar_t>);
logout.imbue(utf8_locale);

if (!logout.is_open()) 
{
 printf("Cannot open file.\n"); 
 return 1; 
}
else printf("Log file created.\n");

logout << "Client IP            │"<< "Recv time                │"<< "Request               │"<< "Response     "<<endl;
logout << "─────────────────────┼"<< "─────────────────────────┼"<<endl;

In my_log.txt file all unicode symbols are replaced with "?????". I want to create something like a log file table. If i use standart ASCII symbols like "---"it will work, and they all are shown surrectly. Ive tried to change global locale, but i dont succeed.


Solution

  • This is why we don't use anything but ASCII in string literals.

    Your code is fine, but your string literals evidently don't contain what you think they do. This is probably due to a misconfigured or underfeatured text editor.

    Use escape sequences instead (\uXXXX) so you know what you're getting. In 2015 you can't really go wrong with source code formed from ASCII characters.