I've created:
#include <streambuf>
#include <iostream>
#include <windows.h>
template<typename T>
class BufferedStream : T
{
private:
T &stream;
std::streambuf* buffer; //planning to use this to create other "IO" functions.
public:
BufferedStream(T &stream) : stream(stream), buffer(stream.rdbuf()) {}
~BufferedStream() {stream.rdbuf(this->buffer);};
std::ostream& operator << (const char* data);
std::ostream& operator << (const std::string &data);
std::wostream& operator << (const wchar_t* data);
std::wostream& operator << (const std::wstring &data);
};
template<typename T>
std::ostream& BufferedStream<T>::operator << (const char* data)
{
SetConsoleOutputCP(CP_UTF8);
DWORD slen = lstrlenA(data);
WriteConsoleA(GetStdHandle(STD_OUTPUT_HANDLE), data, slen, &slen, nullptr);
return *this;
}
template<typename T>
std::ostream& BufferedStream<T>::operator << (const std::string &data)
{
SetConsoleOutputCP(CP_UTF8);
DWORD slen = data.size();
WriteConsoleA(GetStdHandle(STD_OUTPUT_HANDLE), data.c_str(), data.size(), &slen, nullptr);
return *this;
}
template<typename T>
std::wostream& BufferedStream<T>::operator << (const wchar_t* data)
{
DWORD slen = lstrlenW(data);
WriteConsoleW(GetStdHandle(STD_OUTPUT_HANDLE), data, slen, &slen, nullptr);
return *this;
}
template<typename T>
std::wostream& BufferedStream<T>::operator << (const std::wstring &data)
{
DWORD slen = data.size();
WriteConsoleW(GetStdHandle(STD_OUTPUT_HANDLE), data.c_str(), slen, &slen, nullptr);
return *this;
}
BufferedStream<std::ostream> unicout(std::cout);
BufferedStream<std::istream> unicin(std::cin);
int main()
{
const char s[] = "Русский текст в консоли\n";
unicout<<s;
}
because of this problem I'm having: http://stackoverflow.com/questions/21370710/unicode-problems-in-c-but-not-c
Anyway, the problem states that I can use unicode in C but not in C++. I have no clue why as I did everything right. I however found that the above class which I wrote to combat this problem works just fine. I want to know if there is a better way to do this at all?
Any ideas?