gpt4 book ai didi

c++ - 将字符串转换为 LPCTSTR

转载 作者:太空狗 更新时间:2023-10-29 21:43:32 24 4
gpt4 key购买 nike

我在编写代码时遇到了问题。我使用一个函数,该函数将类型为 LPCSTR 的参数对象作为参数对象。对象声明如下所示:LPCTSTR lp文件名;首先,我使用定义的变量,它被进一步分配给 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*。所以,解决方案:

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

关于c++ - 将字符串转换为 LPCTSTR,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22689859/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com