简体   繁体   English

C ++将未终止的char *连接到std :: string

[英]C++ concatenating an unterminated char* to std::string

What is a good way to convert an unterminated char* into a std::string? 未终止的 char *转换为std :: string的好方法是什么? For example, upon completion of the following, 例如,完成以下操作后,

int bytes = recv(_socket, &_recv_buffer, recv_buffer_len, 0)

I have the address of the receive buffer, and the number of bytes it contains, and I want to concatenate it to a std::string . 我有接收缓冲区的地址及其包含的字节数,我想将其连接到std :: string (FWIW, I'm not working with multibyte character sets.) The fallback would be to make the _recv_buffer one byte larger than recv_buffer_len , and set _recv_buffer[bytes] = '\\0' , but I wondered if there were a less sloppy way. (FWIW,我不使用多字节字符集。)后备方法是使_recv_bufferrecv_buffer_len大一个字节,并设置_recv_buffer [bytes] ='\\ 0' ,但是我想知道是否有一种更宽松的方法。

std::string has an append method that takes both a pointer to a string and a length: std::string有一个append方法,该方法同时使用指向字符串的指针和长度:

string& append (const char* s, size_t n);

For you: 为了你:

myString.append(_recv_buffer, bytes);

Editorial note: watch out for identifiers that start with _ . 编者注:请注意以_开头的标识符。 They're reserved for use by the implementation. 它们保留供实现使用。

Use str.append(recv_buffer, bytes); 使用str.append(recv_buffer, bytes); which should do the trick. 这应该可以解决问题。

std::string data(&_recv_buffer, &_recv_buffer + bytes);

And are you sure about the &_recv_buffer ? 您确定&_recv_buffer吗? If your buffer is a char[] or something similiar it must be _recv_buffer . 如果您的缓冲区是char[]或类似名称,则必须为_recv_buffer

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

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