简体   繁体   English

如何将char数组文本存储在字符串中?

[英]How to store a char arrays text in a string?

ref:c++ example code at bottom from http://msdn.microsoft.com/en-us/library/windows/desktop/ms740120(v=vs.85).aspx I have a char array 来自http://msdn.microsoft.com/zh-cn/library/windows/desktop/ms740120(v=vs.85).aspx底部的ref:c ++示例代码我有一个char数组

char RecvBuf[1024];

which gets filled up on receiving UDP message. 在收到UDP消息时被填满。 How do I store it in a std::string variable like string str; 如何将其存储在std :: string变量中,例如string str; so that I can return a string from my function? 这样我就可以从函数中返回一个字符串?

Use this constructor of std::string : 使用此std::string构造函数:

string ( const char * s, size_t n );

Basically, if RecvBuf is a standard (text) "string", it's OK just to make 基本上,如果RecvBuf是标准(文本)“字符串”,则只需

std::string str( RecvBuf );

but this will copy all char s, until \\0 is hit. 但这将复制所有char ,直到命中\\0为止。


And as this buffer stores raw bytes, received from a socket, you should expect \\0 bytes. 由于此缓冲区存储从套接字接收的原始字节,因此您应该期望\\0个字节。

When you receive the data, you'll know it's size. 收到数据后,您会知道它的大小。 So, just use 因此,只需使用

std::string str( RecvBuff, buff_len );

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

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