473,387 Members | 1,483 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

std::string -> WCHAR*

How to convert a std::string to a WCHAR* ?

is there any methods or something ? I can't find. Thanks
Jul 22 '05 #1
12 28088

"Flzw" <fl****@wanadoo.fr> wrote in message
news:cg**********@news-reader3.wanadoo.fr...
How to convert a std::string to a WCHAR* ?

is there any methods or something ? I can't find. Thanks


Well, I tried to use
typedef std::basic_string<WCHAR> wstring;

and then I would use c_str() to get WCHAR*

the program compiles fine but it crashes on
wstring wstr = L"Test";

it seems to trigger a bad alloc and crash somewhere in an internal strlen
call

I know I can convert a basic std:string by getting the c_str() and then
copying it to a ushort array with std:copy but as it is an often called
function, I'd rather want it to be fast, using WCHAR to build strings would
be great.
Jul 22 '05 #2
Le dimanche 29 août 2004 à 11:46:47, Flzw a écrit dans comp.lang.c++*:
How to convert a std::string to a WCHAR* ?

is there any methods or something ? I can't find. Thanks


The closest-to-standard way I can see is:

#include <cstdlib>
#include <string>
....

const std::string input = "string to convert";

// null-call to get the size
size_t needed = ::mbstowcs(NULL,&input[0],input.length());

// allocate
std::wstring output;
output.resize(needed);

// real call
::mbstowcs(&output[0],&input[0],input.length());

// You asked for a pointer
wchar_t *pout = output.c_str();

--
___________ 2004-08-29 12:47:10
_/ _ \_`_`_`_) Serge PACCALIN -- sp ad mailclub.net
\ \_L_) Il faut donc que les hommes commencent
-'(__) par n'être pas fanatiques pour mériter
_/___(_) la tolérance. -- Voltaire, 1763
Jul 22 '05 #3
On Sun, 29 Aug 2004 11:46:47 +0200, "Flzw" <fl****@wanadoo.fr> wrote:
How to convert a std::string to a WCHAR* ?
is there any methods or something ? I can't find. Thanks


<OT-rant>
WCHAR is a non-standard Windows type. Therefore, it is off-topic in
comp.lang.c++ which concerns itself only with ANSI and ISO standard
C++ language topics. Please read the FAQ for this newsgroup at:
http://www.parashift.com/c++-faq-lite/
</OT-rant>

Nevertheless, you are stuck with a std::string and need to know what
to do with it. It depends on how the std::string's character data is
encoded, i.e. which locale or code page is used.

Fr starters, I will assume you know that there are several different
Unicode encodings (http://www.unicode.org). WCHAR is defined as a
"16-bit Unicode character" which is only one of them.

For data which comes from Western European code set (i.e. ISO-8859-1
or ISO-8859-15), the conversion is trivial since the MSB (most
significant byte) is always 0. You need to supply a buffer of WCHAR,
which is large enough to contain all the character data plus one
terminating null WCHAR, and merely copy the characters from the
string. Don't use memcpy or such, but use a loop and copy it character
by character into the buffer. If the buffer is allocated dynamically,
be sure to release the memory by calling delete[] (if you used new[])
when you are done, or else use a smart pointer which can handle array
data (std::auto_ptr<> cannot ... there are such smart pointers in the
Boost library, though: http:://www.boost.org ).

Since your post seems to originate in France, be aware that the Euro
character "€" has a Unicode encoding of 0x20ac, therefore the MSB is
*not* zero for this particular character. In Windows, it is defined as
0x80 which is (AFAIK) a non-printable character in ISO-8859-1 code
page.

If there is a different code set involved, you will need to use either
the libraries supplied by the framework you are using for development
(e.g. MFC, VCL on Borland) or use the Windows API functions suitable
for this.

Your compiler may have implemented locale facets which facilitate some
conversions via std::[w]iostream, e.g. check out:

std::ios_base::imbue(const std::locale &)).

Note that some library functions for COM/OLE on Windows expect a BSTR
argument, or return a BSTR, which is a non-standard OLE data type
although I believe it is defined as WCHAR*. This is a horse of an
entirely different color, and there are issues with memory management
which are OS-specific. If this is what you need, go to one of the
Microsoft newsgroups which deals with Windows-specific C++
development.

--
Bob Hairgrove
No**********@Home.com
Jul 22 '05 #4
> std::wstring output;

Thanks, I decided to use wstring everywhere so I don't have to bother with
conversions (because I would need a lot of them and it would affect
efficiency)

the problem I have with wstring is when I initialise it for example

wstring test = L"Test";

Compiles, but crashes, seems to trigger a bad alloc and crash in some
internal strlen call

any idea on this ?
Jul 22 '05 #5
Flzw wrote:
How to convert a std::string to a WCHAR* ?

is there any methods or something ? I can't find. Thanks

WCHAR is a system-dependent type, so I will use wchar_t for a portable
example:

#include <string>
int main()
{
using namespace std;

string s="This is a test";

wchar_t *p=new wchar_t[s.size()];
for(string::size_type i=0; i<s.size(); ++i)
p[i]=s[i];
}


Regards,

Ioannis Vranos

http://www23.brinkster.com/noicys
Jul 22 '05 #6
Flzw wrote:
Well, I tried to use
typedef std::basic_string<WCHAR> wstring;

and then I would use c_str() to get WCHAR*

the program compiles fine but it crashes on
wstring wstr = L"Test";

it seems to trigger a bad alloc and crash somewhere in an internal strlen
call

wstring is an existing C++ string type defined in <string>. You can use
it directly.

I know I can convert a basic std:string by getting the c_str() and then
copying it to a ushort array with std:copy

Huh?
but as it is an often called
function, I'd rather want it to be fast, using WCHAR to build strings would
be great.

You can.
#include <string>
int main()
{
using namespace std;

wstring s=L"This is a test";
}


Regards,

Ioannis Vranos

http://www23.brinkster.com/noicys
Jul 22 '05 #7
Flzw wrote:
std::wstring output;


Thanks, I decided to use wstring everywhere so I don't have to bother
with conversions (because I would need a lot of them and it would
affect efficiency)

the problem I have with wstring is when I initialise it for example

wstring test = L"Test";

Compiles, but crashes, seems to trigger a bad alloc and crash in some
internal strlen call

any idea on this ?


Either you're doing something else that corrupts memory before or your
implementation has a bug. The following program works here:

#include <iostream>
#include <string>

int main()
{
std::wstring str = L"Hello, world";
std::wcout << str << std::endl;
}

Jul 22 '05 #8
On Sun, 29 Aug 2004 15:04:20 +0300, Ioannis Vranos
<iv*@guesswh.at.grad.com> wrote:
wchar_t *p=new wchar_t[s.size()];


I'm glad I'm not the only one that does this sometimes <g>

....should be:

wchar_t *p=new wchar_t[s.size()+1];

--
Bob Hairgrove
No**********@Home.com
Jul 22 '05 #9
Bob Hairgrove wrote:
On Sun, 29 Aug 2004 15:04:20 +0300, Ioannis Vranos
<iv*@guesswh.at.grad.com> wrote:

wchar_t *p=new wchar_t[s.size()];

I'm glad I'm not the only one that does this sometimes <g>

...should be:

wchar_t *p=new wchar_t[s.size()+1];


Yes that could be reasonable for char *, but why for wchar_t*?


Regards,

Ioannis Vranos

http://www23.brinkster.com/noicys
Jul 22 '05 #10
On Mon, 30 Aug 2004 01:12:11 +0300, Ioannis Vranos
<iv*@guesswh.at.grad.com> wrote:
Bob Hairgrove wrote:
On Sun, 29 Aug 2004 15:04:20 +0300, Ioannis Vranos
<iv*@guesswh.at.grad.com> wrote:

wchar_t *p=new wchar_t[s.size()];

I'm glad I'm not the only one that does this sometimes <g>

...should be:

wchar_t *p=new wchar_t[s.size()+1];


Yes that could be reasonable for char *, but why for wchar_t*?


Same as for char * ... to delimit the end of the array with a null
wchar_t, for example when initializing a std::wstring with a wchar_t*.

Of course, one could also use assign() with iterators.

--
Bob Hairgrove
No**********@Home.com
Jul 22 '05 #11
MSD
I am using the following code for converting the std::wstring to
std::string.

#include <cstdlib>
#include <string>
......
std::string strName;
std::wstring wstrName (L"ABCDEF");

if (wstrName.size() > 0)
{
int len = wcslen(wstrName.c_str());
int c = wcstombs( &strName[0], wstrName.c_str(), 1000);
cout << "len = " << len << "\ncharacters converted = " <<
c << "\n W - Name = " << wstrName << endl;
}

char *ptrName = strName.c_str();
......

This is compiling fine, but as the length of the wstrName increases to
more than 8/9, it gives me Segmentation Fault and crashes.

I suspect some memory troubles, but do not have any solution for this. Do
you have any idea how to solve this?

The max limit for wstrName can go upto 30 in my case.

Thanks

Jul 23 '05 #12
MSD wrote:
I am using the following code for converting the std::wstring to
std::string.

#include <cstdlib>
#include <string>
.....
std::string strName;
std::wstring wstrName (L"ABCDEF");

if (wstrName.size() > 0)
{
int len = wcslen(wstrName.c_str());
int c = wcstombs( &strName[0], wstrName.c_str(), 1000);
cout << "len = " << len << "\ncharacters converted = " <<
c << "\n W - Name = " << wstrName << endl;
}

char *ptrName = strName.c_str();
.....

This is compiling fine, but as the length of the wstrName increases to
more than 8/9, it gives me Segmentation Fault and crashes.
I suspect some memory troubles, but do not have any solution for this. Do
you have any idea how to solve this?


Well, you write up to 1000 characters to the contents of strName without
caring for its size.

Jul 23 '05 #13

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
by: Angus Leeming | last post by:
Hello, Could someone explain to me why the Standard conveners chose to typedef std::string rather than derive it from std::basic_string<char, ...>? The result of course is that it is...
11
by: Christopher Benson-Manica | last post by:
Let's say I have a std::string, and I want to replace all the ',' characters with " or ", i.e. "A,B,C" -> "A or B or C". Is the following the best way to do it? int idx; while(...
22
by: Jason Heyes | last post by:
Does this function need to call eof after the while-loop to be correct? bool read_file(std::string name, std::string &s) { std::ifstream in(name.c_str()); if (!in.is_open()) return false; ...
8
by: Patrick Kowalzick | last post by:
Dear NG, I would like to change the allocator of e.g. all std::strings, without changing my code. Is there a portable solution to achieve this? The only nice solution I can think of, would be...
6
by: Nemok | last post by:
Hi, I am new to STD so I have some questions about std::string because I want use it in one of my projects instead of CString. 1. Is memory set dinamicaly (like CString), can I define for...
2
by: FBergemann | last post by:
if i compile following sample: #include <iostream> #include <string> int main(int argc, char **argv) { std::string test = "hallo9811111z"; std::string::size_type ret;
84
by: Peter Olcott | last post by:
Is there anyway of doing this besides making my own string from scratch? union AnyType { std::string String; double Number; };
11
by: Jacek Dziedzic | last post by:
Hi! I need a routine like: std::string nth_word(const std::string &s, unsigned int n) { // return n-th word from the string, n is 0-based // if 's' contains too few words, return "" //...
11
by: Christopher Pisz | last post by:
Is std::string::npos always going to be less than any std::string 's size()? I am trying to handle a replacement of all occurances of a substr, in which the replacement also contains the substr....
11
by: tech | last post by:
Hi, I need a function to specify a match pattern including using wildcard characters as below to find chars in a std::string. The match pattern can contain the wildcard characters "*" and "?",...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.