changing char to wstring, how?

J

jalkadir

How can I conver a char[x] to std::wstring, for intance
time_t Time_t;
std::wstring Date;
time( &Time_t );
Date = ctime( &Time_t );

or
strd::string wstr;
str = __FILE__;

Isn't the conversion done automatically?
I am using g++ 3.3.x


TIA
 
J

jalkadir

Thanks for the prompt response Roland.
I read the http site and it does exactly what I needed, however, I
wonder if there is pure C++ way to do this, do you know?

Thanks again.
 
J

jalkadir

My test run compiles, but I get a segmentation fault.

gdb.exe reports
#0 0x77c1d2b9 in msvcrt!mblen


What am I doing wrong?
Any body!!

#include <cstdlib>
#include <iostream>
#include <wchar.h>

using namespace std;
std::wstring ctow(const char* src){
wchar_t* dest;
int i = mbstowcs(dest, src, sizeof(src));
return dest;
}
int main(int argc, char *argv[])
{
const char* str = "hola";
std::wstring wstr;
wstr = ctow(str);

system("PAUSE");
return EXIT_SUCCESS;
}
 
M

Mike Wahler

jalkadir said:
My test run compiles, but I get a segmentation fault.

gdb.exe reports
#0 0x77c1d2b9 in msvcrt!mblen


What am I doing wrong?
Any body!!

#include <cstdlib>
#include <iostream>
#include <wchar.h>

using namespace std;
std::wstring ctow(const char* src){
wchar_t* dest;
int i = mbstowcs(dest, src, sizeof(src));

'dest' is not pointing anywhere.

-Mike
 
J

John Harrison

jalkadir said:
My test run compiles, but I get a segmentation fault.

gdb.exe reports
#0 0x77c1d2b9 in msvcrt!mblen


What am I doing wrong?
Any body!!

You don't understand pointers and arrays. You need to C++ text book.
#include <cstdlib>
#include <iostream>
#include <wchar.h>

using namespace std;
std::wstring ctow(const char* src){
wchar_t* dest;

Unitinialised pointer, you need to allocate some memory.
int i = mbstowcs(dest, src, sizeof(src));

sizeof(src) gives the sizeof the pointer (four bytes) not the size of
the string.

strlen(src) seems right.

It would be better like this, using a vector to allocate the necessary
memory.

std::wstring ctow(const char* src){
std::vector<wchar_t> dest(how_ever_many_bytes_you_need);
int i = mbstowcs(&dest[0], src, strlen(src));
return std::wstring(&dest[0]);
}

I don't know how you get the value of 'how_ever_many_bytes_you_need',
I'll leave you to work that out.

If you are a newbie, then don't use pointers when you don't have to,
especially when you don't understand them.

john
 
J

jalkadir

Thanks!! it did the trick, but I still have a lot of questions about
IOStreams, regarding wide stream.

I'll keep posting.

Again, thanks!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,754
Messages
2,569,528
Members
45,000
Latest member
MurrayKeync

Latest Threads

Top