I Want to Convert a std::string to a cstring

Hi all,

I want to convert a std::string to a cstring.

I have found this tutorial but it is for converting a std::string to a "const char" not a "char":
https://www.techiedelight.com/convert-std-string-const-char-cpp/

So how do I convert a std::string to a cstring?

Thanks very much,

Zeb

.c_str()

There is no implemented method to return a char*
You need to make a copy of .c_str()

Sorry I don't quite get what I should do!

I take it that I should use the strcpy command?

Thanks,

Zeb

ZebH:
Sorry I don't quite get what I should do!

I take it that I should use the strcpy command?

Thanks,

Zeb

char str[myString.length() + 1] = {};
strcpy(str, myString.c_str());

ZebH:
I have found this tutorial but it is for converting a std::string to a "const char" not a "char":

c_str() returns a const char*. by const, it means the value cannot be modified (you couldn't process it with strtok() for example.

but you could do char* s = (char*) myString.c_str();

Hi arduino_new,

What am I supposed to put inside of the brakets?

char str[myString.length() + 1] = {};

Thanks for your help,

Zeb

ZebH:
Hi arduino_new,

What am I supposed to put inside of the brakets?

char str[myString.length() + 1] = {};

Thanks for your help,

Zeb

Nothing, it is to initialize all element of the array to 0.

gcjr:
c_str() returns a const char*. by const, it means the value cannot be modified (you couldn't process it with strtok() for example.

but you could do char* s = (char*) myString.c_str();

I would suggest against doing this. This would leave the object at inconsistent state.

Excellent it is working great!

Thank you all, for your help!

Thanks again,

Zeb

arduino_new:
I would suggest against doing this. This would leave the object at inconsistent state.

what about

Serial.println (s.c_str());

gcjr:
what about

Serial.println (s.c_str());

What about it?

In C++17, you can use string::data(): std::basic_string<CharT,Traits,Allocator>::data - cppreference.com

Some caveats:

  1. Modifying the character array accessed through the const overload of data has undefined behavior.
  2. Modifying the past-the-end null terminator stored at data()+size() to any value other than CharT() has undefined behavior.

If the compiler that comes with your board package is new enough, you can enable C++17 in the platform.txt file by changing -std=gnu++11 to -std=gnu++1z or -std=gnu++17.

Pieter

Excellent, thank you!