Reading raw byte array into std::string

前端 未结 2 396
我寻月下人不归
我寻月下人不归 2021-01-18 16:18

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 l         


        
相关标签:
2条回答
  • 2021-01-18 16:39

    Yes, after C++11.

    But you cant use s.data() as it returns a char const*

    Try:

    std::string s(100, '\0');
    recv_n(handle, &s[0], 100);
    

    Depending on situation, I may have chosen a std::vector<char> especially for raw data (though it would all depend on usage of the data in your application).

    0 讨论(0)
  • 2021-01-18 16:46

    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).

    0 讨论(0)
提交回复
热议问题