Question

I encountered a problem during writting my code. I use a function which take as an argument object which type is LPCSTR. The object declaration looks like shown below: LPCTSTR lpFileName; Firstly, I used defined variable, which was futher assign to lpFileName like this:

#define COM_NR L"COM3"
lpFileName = COM_NR

Using this manner, I could easily pass lpFileName argument to the function. Anyway, i had to changed the way of defining my port number. Currently i read text from *.txt file and save it as string variable e.g "COM3" or "COM10". The main problem is to convert string to LPCSTR properly. I found good solution but finally it doesn't seem working properly. My code looks like this:

string temp;
\\code that fill temp\\
wstring ws;
ws.assign(temp.begin(),temp.end());

I thought that conversion went correctly, maybe it did and I don't get it because when i print few things it makes me to wonder why it doesn't work as i want: cout temp_cstr(): COM3 cout LCOM3: 0x40e586 cout ws.c_str(): 0x8b49b2c

Why LCOM3 and ws.c_str() doesn't contain the same? When i pass lpFileName = ws.c_str() to my function, it works uncorretly. On the other hand, passing lpFileName = L"COM3" gives success. I code using cpp, and IDE is QtCreator

Was it helpful?

Solution

Eventually, I managed with the pitfall using conversion-function s2ws() and doing few operations. I place my soultion here for people who will have similar troubles with converting string. In my first post i wrote that i needed to convert string to LPCTSTR and finally it turned out that argument in my function is not, LPCTSTR but LPCWSTR that is const wchar_t*. So, soulution:

string = "COM3";
wstring stemp;
LPCWSTR result_port;
stemp = s2ws(port_nr);
result_port = stemp.c_str(); // now passing result_port to my function i am getting success

declaration of s2ws:

wstring s2ws(const std::string& s)
{
    int len;
    int slength = (int)s.length() + 1;
    len = MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, 0, 0);
    wchar_t* buf = new wchar_t[len];
    MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, buf, len);
    std::wstring r(buf);
    delete[] buf;
    return r;
}

OTHER TIPS

Try to use wostringstream:

string temp;
\\code that fill temp\\
wostringstream ost;
ost << temp.c_str();
wstring ws = ost.str();

I have struggled with this for quite a while. After quite a bit of digging I found this works the best; you could try this.

std::string t = "xyz";
CA2T wt (t.c_str());
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top