Sign in to follow this  

overiding ostream

This topic is 4206 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hello, Is it possible to override ostream to stream wstring's? In other words, is the following possible:
std::wstring str = _T("test");
std::ofstream file("test.txt");

file << str;

Share this post


Link to post
Share on other sites
You'll have to write the overload yourself, using the appropriate locale facet. The function templates in <string> only cover the case where the character type is the same in the string and the stream.

template<class E, class T, class A>
basic_ostream<E, T>& operator<<( basic_ostream<E, T>& os,
const basic_string<E, T, A>& str )

Share this post


Link to post
Share on other sites
When, you use std::string or std::ofstream you're using templates whether you know it or not. In any case, if all you care about is writing wstrings, then you might consider using std::wofstream instead of std::ofstream.

Share this post


Link to post
Share on other sites
So, I switched to wofstream and to my disgust, it errors on this line:

m_ofFile << std::setw(2) << std::setfill('0') << pTime.tm_hour << ":" <<
std::setw(2) << std::setfill('0') << pTime.tm_min << ":" << std::setw(2) <<
std::setfill('0') << pTime.tm_sec << std::endl;

With this error:

error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'std::_Fillobj<_Elem>' (or there is no acceptable conversion)

Please interpret

Thanks,
exorcist_bob

Share this post


Link to post
Share on other sites
You're trying to set the fill element to a narrow character when the stream is used for wide characters. Remember '0' is of type char.

Share this post


Link to post
Share on other sites
Quote:
error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'std::_Fillobj<_Elem>' (or there is no acceptable conversion)


That's not the whole error message. Pay close attention to what _Elem is: "with _Elem=wchar_t ... and _Elem=char".

std::setfill('0') is a std::_Fillobj<char>. You want a std::_Fillobj<wchar_t> and thus need to write std::setfill(L'0').

Share this post


Link to post
Share on other sites

This topic is 4206 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this