开发者

How to convert win32 CHAR(char) type to std string?

Im using the win32 function ReadFile:

CHAR 开发者_Python百科lpBuffer[256];
DWORD nBytesRead;
DWORD nCharsWritten;

ReadFile(hPipeRead,lpBuffer,sizeof(lpBuffer),
                                      &nBytesRead,NULL) || !nBytesRead)

now im catcing the response from stdout in to lpBuffer with this i like to convert it to std string , the problem is when i do simple :

std::string szReturnlpBuffer(lpBuffer); 

the value of the szReturnlpBuffer contains alot of garbege carecthers after the real string: its looks like this the szReturnlpBuffer value :

"Im stdout from the Qt applicationÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌ"

what im doing wrong here ?


You need to specify the size of the string:

std::string szReturnlpBuffer(lpBuffer, nBytesRead); 

because otherwise it reads till it finds a null character, which causes undefined behavior when it gets outside lpBuffer's memory.


You need to terminate the string with a null character:

lpBuffer[nBytesread] = '\0';
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜