ccoding
ccoding

Reputation: 1

Convert char array to CString in c++

I am unable to convert the char * to CString.. the last 2 print lines print nothing...I need it as part of cstring to be able to pass it to a function..

char result[500];
strcpy(result, "\\\\.\\pipe\\");                    
strcat(result, a["BLOB"][i].GetString());// just appending to "result" a string I am reading from json file..
CString  temp(result);
printf("\n1-The pipeName we are looking at is %s \n", result);
printf("\n2-The pipeName we are looking at is %s \n", temp);
printf("\n3-The pipeName we are looking at is %s \n", CString(result,500));

Upvotes: 0

Views: 3469

Answers (3)

dxiv
dxiv

Reputation: 17638

Build the string directly into the CString, and use the builtin cast to const char * when printing.

CString  temp("\\\\.\\pipe\\");
temp += a["BLOB"][i].GetString(); // or: temp.Format("\\\\.\\pipe\\%s", a["BLOB"][i].GetString());
printf("-The pipeName we are looking at is %s\n", (const char *)temp);

Upvotes: 2

TheUndeadFish
TheUndeadFish

Reputation: 8171

printf is crude. Using %s with printf will assume that the first pointer-size amount of bytes in whatever you pass to it are actually a pointer to a string (aka char*).

That may or may not be true for CString. In your case it seems that it isn't.

To use printf you need to do it more like:

printf("\n2-The pipeName we are looking at is %s \n", temp.GetString());

Or else just stop using printf and use something with more type-safety, such as cout

Upvotes: 2

Tanveer Badar
Tanveer Badar

Reputation: 5523

How would printf() know what CString is? What a class is? How to convert CString to a c-style string?

This is working as expected.

What you are looking for is probably documented here, based on the assumption that MFC/WFC also provide a CString.

Upvotes: 1

Related Questions