473,587 Members | 2,605 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 28150

"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_stri ng<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(n eeded);

// real call
::mbstowcs(&out put[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**********@Ho me.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::siz e_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_stri ng<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**********@Ho me.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

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

Similar topics

10
8160
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 effectively impossible to forward declare std::string. (Yes I am aware that some libraries have a string_fwd.h header, but this is not portable.) That said, is there any real reason why I can't derive an otherwise empty
11
3632
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( (idx=str.find_first_of(',')) >= 0 ) { str.replace( idx, 1, "" ); str.insert( idx, " or " ); }
22
13229
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; char c; std::string str;
8
9177
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 a namespace and another typedef to basic_string: namespace my_string {
6
11492
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 example string str1; as a class member and then add text to it. or do I have to specify it's length when defining? 2. How to convert from std::string to LPCSTR
2
5488
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
15830
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
2888
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 "" // 'words' are any sequences of non-whitespace characters // leading, trailing and multiple whitespace characters // should be ignored.
11
4246
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. Yick. All I could come up with is: #include <string> int main() { std::string text;
11
4819
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 "?", where "*" matches zero or more consecutive occurrences of any character and "?" matches a single occurrence of any character. Does boost or some other library have this capability? If boost does have this, do i need to include an entire
0
8220
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8352
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8222
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5396
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
3846
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
3882
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2367
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1457
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1194
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.