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

1k Views Asked by At

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;
}
2

There are 2 best solutions below

7
On BEST ANSWER

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);
2
On

You could provide an appropriate constructor for Person.

Person(std::string Name) : Name(std::move(Name)) {}

Definition of a Person would be

Person ps(std::string(buf, 10));

Or write directly:

Users.emplace_back( std::string(buf, 10) );