简体   繁体   English

如何将win32 CHAR(char)类型转换为std字符串?

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

Im using the win32 function ReadFile: 我正在使用win32函数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 : 现在我希望从stdout输入响应到lpBuffer,我想将其转换为std字符串,问题是当我做简单时:

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 : szReturnlpBuffer的值在真实字符串之后包含大量garbege carecthers:看起来像szReturnlpBuffer值:

"Im stdout from the Qt applicationÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌ" “我来自Qt应用程序的标准输出ÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌ”

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. 因为否则它将一直读取直到找到一个空字符,当它到达lpBuffer的内存之外时会导致未定义的行为。

您需要使用空字符来终止字符串:

lpBuffer[nBytesread] = '\0';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM