将原始字节数组读入std :: string [英] Reading raw byte array into std::string
问题描述
我一直在想着下面的问题:假设我有一个C风格函数读取原始数据到缓冲区
int recv_n(int handle,void * buf,size_t len);
我可以直接读取数据到 std:string
或 stringstream
,而不分配任何临时缓冲区?例如,
std :: string s(100,'\0');
recv_n(handle,s.data(),100);
我想这个解决方案有一个未定义的结果,因为,afaik, string: :c_str
和 string :: data
可能返回一个时间位置,并不一定将指针返回到内存中的真实位置,
为什么不能使用向量< char>
而不是 string
?您可以这样做:
矢量< char> v(100,'\0');
recv_n(handle,& v [0],100);
这似乎对我来说很惯用,特别是因为你不使用它作为字符串它是原始数据)。
I've been wondering about the following issue: assume I have a C style function that reads raw data into a buffer
int recv_n(int handle, void* buf, size_t len);
Can I read the data directly into an std:string
or stringstream
without allocating any temporal buffers? For example,
std::string s(100, '\0');
recv_n(handle, s.data(), 100);
I guess this solution has an undefined outcome, because, afaik, string::c_str
and string::data
might return a temporal location and not necessarily return the pointer to the real place in the memory, used by the object to store the data.
Any ideas?
Why not use a vector<char>
instead of a string
? That way you can do:
vector<char> v(100, '\0');
recv_n(handle, &v[0], 100);
This seems more idiomatic to me, especially since you aren't using it as a string (you say it's raw data).
这篇关于将原始字节数组读入std :: string的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!