将字符串转换为LPCTSTR

Converting string to LPCTSTR

本文关键字:LPCTSTR 转换 字符串      更新时间:2023-10-16

我在编写代码时遇到了一个问题。我使用一个函数作为参数对象,它的类型是LPCSTR。对象声明如下所示:LPCTSTR lpFileName;首先,我使用了已定义的变量,然后像这样将其分配给lpFileName:

#define COM_NR L"COM3"
lpFileName = COM_NR

使用这种方式,我可以很容易地将lpFileName参数传递给函数。总之,我必须改变定义端口号的方式。目前我从*.txt文件中读取文本,并将其保存为字符串变量,例如"COM3"或"COM10"。主要问题是如何正确地将字符串转换为LPCSTR。我找到了很好的解决方案,但最后它似乎不能正常工作。我的代码是这样的:

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

我认为转换是正确的,也许它做了,我没有得到它,因为当我打印一些东西时,它让我想知道为什么它不像我想要的那样工作:cout temp_cstr(): COM3cout LCOM3: 0x40e586Cout ws.c_str(): 0x8b49b2c

为什么LCOM3和ws.c_str()不包含相同的?当我将lpFileName = ws.c_str()传递给我的函数时,它工作不正确。另一方面,传递lpFileName = L"COM3"则表示成功。我用cpp编码,IDE是QtCreator

最后,我使用转换函数s2ws()处理了这个缺陷,只做了很少的操作。我把我的解决方案在这里的人谁会有类似的问题与转换字符串。在我的第一篇文章中,我写道,我需要将字符串转换为LPCTSTR,最后证明我的函数中的参数不是LPCTSTR,而是LPCWSTR,即const wchar_t*。所以,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

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;
}

尝试使用wostringstream:

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

我已经为此挣扎了很长一段时间。经过相当多的挖掘,我发现这是最好的;你可以试试这个

std::string t = "xyz";
CA2T wt (t.c_str());