Sign in to follow this  
slyterence

narrowing wstrings

Recommended Posts

slyterence    100
Hi, I'm trying to write a wide string into a std::ostringstream as follows
for(int i = 0; i < temp.length(); ++i)
{
	oss << oss.narrow(temp[i], '%');
}


and I get the following error:
c:\...\file.cpp : warning C4244: 'argument' : conversion from 'std::allocator<_Ty>::value_type' to 'char', possible loss of data
        with
        [
            _Ty=wchar_t
        ]


Is there a better (standard) way of doing this? Particularly, I'd prefer to convert the wstring into a string, and then just append that to the ostringstream, because then I can reuse the narrowing conversion wherever I want from a conversion class. I tried boost::lexical_cast, but that didn't work, so I'm a bit stumped. Thanks

Share this post


Link to post
Share on other sites
Code-R    136
here's something I made that we use at work:

//# Sherief "JD" N. Farouk
//# Created: Saturday, August 13, 2005, 3:33:37 PM
//# Last Modified: Monday, August 15, 2005, 9:50:54 PM
//# ext-h-gen-dep-std-boost-nolib
#ifndef __EXT_LEXICAL_CAST_H__
#define __EXT_LEXICAL_CAST_H__

#pragma once

#include <string>
#include <locale>

#include <boost/lexical_cast.hpp>

namespace boost
{
template<>
std::wstring lexical_cast<std::wstring, std::string>(std::string arg)
{
std::wstring result;
std::locale loc;
for(unsigned int i= 0; i < arg.size(); ++i)
{
result += std::use_facet<std::ctype<wchar_t> >(loc).widen(arg[i]);
}
return result;
}

template<>
std::string lexical_cast<std::string, std::wstring>(std::wstring arg)
{
std::string result;
std::locale loc;
for(unsigned int i= 0; i < arg.size(); ++i)
{
result += std::use_facet<std::ctype<wchar_t> >(loc).narrow(arg[i]);
}
return result;
}
}

#endif



Hope you find it useful.

Share this post


Link to post
Share on other sites

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