Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/ant/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何将tstringstream的内容传递给接收LPTSTR的方法?_C++_Visual C++_Stream_Type Conversion_Stringstream - Fatal编程技术网

C++ 如何将tstringstream的内容传递给接收LPTSTR的方法?

C++ 如何将tstringstream的内容传递给接收LPTSTR的方法?,c++,visual-c++,stream,type-conversion,stringstream,C++,Visual C++,Stream,Type Conversion,Stringstream,我尝试了以下方法: tstringstream s; s << _T("test") << std::endl; LPTSTR message = s.str().c_str(); Log(5, _T("Example", message); 但我得到了以下错误: Error: A value of type "const char *" cannot be used to initialize an entity of type "LPTSTR" 但我不确定如何处理

我尝试了以下方法:

tstringstream s;
s << _T("test") << std::endl;
LPTSTR message = s.str().c_str();
Log(5, _T("Example", message);
但我得到了以下错误:

Error: A value of type "const char *" cannot be used to initialize an entity of type "LPTSTR"

但我不确定如何处理这种转换。在我的例子中,我正在使用MSVC++编译器编译一个多字节字符集应用程序。在这些条件下,LPTSTR被定义为一个LPSTR,它被定义为一个字符*

您正在点击的
const
-不兼容。出于某种原因,函数
Log
使用指向可变数据的指针,该指针与
c_str()
返回的
const
数据的指针不兼容

如果可以选择,请更改
Log
,将其参数设置为
const
(我假设它实际上没有修改传入的字符串):

同样,将
消息声明为
LPCTSTR

还要注意的是,您不能按现在的方式初始化
消息
:由
str()
返回的字符串是临时的,因此您必须存储它:

tstring message = s.str();
Log(5, _T("Example", message.c_str());
如果
Log
不在您的控制范围内,但您知道它不修改它的参数,您可以使用
常量转换

LPTSTR message = const_cast<LPTSTR>(message.c_str());  // `message` changed as above

我可以看到一些问题

首先:

LPTSTR message = s.str().c_str();
调用
s.str()。因此,调用
c_str()
返回的地址无效。您需要一个临时的本地:

string str = s.str();
LPCTSTR message = str.c_str();
由于
c_str()
返回一个常量c字符串,所以您也需要将消息声明为常量c字符串

另一个问题是,
Log
函数接收一个非常量C字符串,但
C_str()
返回一个常量C字符串。假设
Log
函数不需要修改消息,那么为什么要请求可修改的缓冲区呢。更改
Log
以接收常量C字符串:

void Log(..., LPCTSTR szMsgString, ...)

<>最后,因为这是C++,你为什么要使用C字符串呢?最好使用C++字符串。

发布的代码有一个悬空指针(名为代码>消息<代码>),作为“<代码> STD::String < /Cord>>对象,在代码结束时,通过<代码> CyString()/<代码>返回<代码> char */COD>。
LPTSTR message = s.str().c_str();
string str = s.str();
LPCTSTR message = str.c_str();
void Log(..., LPCTSTR szMsgString, ...)