将字符串转换为LPCTSTR

时间:2014-03-27 13:58:39

标签: c++ string qt-creator

我在编写代码时遇到了问题。我使用一个函数作为参数对象,其类型是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():COM3 cout LCOM3:0x40e586 cout ws.c_str():0x8b49b2c

为什么LCOM3和ws.c_str()不包含相同的内容?当我将lpFileName = ws.c_str()传递给我的函数时,它无法正常工作。另一方面,传递lpFileName = L“COM3”会成功。 我使用cpp编写代码,IDE是QtCreator

3 个答案:

答案 0 :(得分:2)

最终,我使用转换函数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;
}

答案 1 :(得分:0)

尝试使用wostringstream

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

答案 2 :(得分:0)

我已经挣扎了很长一段时间。经过相当多的挖掘后,我发现这种方法效果最好;你可以试试这个。

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