user63898
user63898

Reputation: 30885

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

Im using the win32 function ReadFile:

CHAR 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 ?

Upvotes: 1

Views: 900

Answers (2)

ralphtheninja
ralphtheninja

Reputation: 132978

You need to terminate the string with a null character:

lpBuffer[nBytesread] = '\0';

Upvotes: 1

Yakov Galka
Yakov Galka

Reputation: 72449

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.

Upvotes: 3

Related Questions