Search code examples
c++stdstringstdlist

how to copy part of char buffer to std::string?


I try to store instances of class Person in std::list Users. Before putting each instance to Users I want to copy first 10 bytes from buf to std::string Name. How can I do that?

class Person {
  public:   
   Person(){ std::cout << "Constructing Person " << std::endl;}
  private:
   std::string Name;
};

int main() {

  unsigned char buf[1024];
  std::list<Person> Users;

  Person ps;
  Users.push_back(ps);

  return 0;
}

Solution

  • You'll need to change your constructor for doing this:

    class Person {
      public:   
       Person(const char* buf_, size_type size_) 
       : name(buf_,size_) { 
           std::cout << "Constructing Person " << std::endl;
       }
       // ....
    };
    

    and in main() write

    Person ps(buf,10);