简体   繁体   中英

C++ convert std::string to char

I have following scenario:

struct MyStruct
{
  char name[25];
  char address[12];
}

Somewhere::SomeMethod(std::shared_ptr<SomeArgumentClass> args)
{
  // GetName() and GetAddress() both return std::strings
  ::MyStruct newValue = {args->GetName(), args->GetAddress()};
  // add newValue to some structure that needs to have chars
}

Error:

error C2440: 'initializing' : cannot convert from 'std::string' to 'char'
error C2440: 'initializing' : cannot convert from 'std::string' to 'char'

I am not able to get my std::string converted to a char.

Thanks a lot!

Firstly, your terminology is incorrect. You don't want to convert to char , which is a single character. I realise that the error message claims you're trying to convert to char , but that's because your incorrect code has confused the compiler into thinking you're trying to initialise individual elements of the array name . Be wary of the specifics of an error message when you write the wrong code, because the compiler cannot read your mind — it can only go off of what you've written!

In reality you want to copy the characters inside your std::string , into the array of char , that is your member.

Like so:

Somewhere::SomeMethod(std::shared_ptr<SomeArgumentClass> args)
{
   const auto& name = args->GetName();
   const auto& address = args->GetAddress();

   ::MyStruct newValue;
   std::copy(std::begin(name), std::end(name), &newValue.name[0]);
   std::copy(std::begin(address), std::end(address), &newValue.address[0]);

   // add newValue to some structure that needs to have chars
}

But you need to add bounds checking too. To do that, roughly I might consider replacing each std::copy call with something like:

std::copy_n(
   &name[0],
   std::min(name.size(), sizeof(newValue.name)),
   &newValue.name[0]
);

You'll also need some null termination depending on how many characters were copied.

Generally though the salient point is that you need to actually copy those characters because there is no one-step way to do it. It stems in part from how arrays can't be assigned-to, but also from the fact that their dimensions are part of the type which makes things more complicated.

If this seems like a pain in the arse, that's because it is — ideally you would stick with std::string across the board because it's far superior, and was specifically introduced to make it easier to handle arrays of char . You can still pass a const char* (or char* !) pointing to the string's data into a C API. Of course if ::MyStruct itself is a third-party C type, you have no choice but to do it the hard way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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