简体   繁体   中英

What is the simplest way to convert a const char[] to a string in c++

Is there a simple way of creating a std::string out of an const char[] ?

I mean something simpler then:

std::stringstream stream;
stream << const_char;

std::string string = stream.str();

std::string has multiple constructors, one of which is string( const char* str ); .

You can use it like this:

std::string myString(const_char);

You could also use assignment, if you need to set the value at some time later than when the variable is declared:

myString = const_char;

std::string has a constructor that takes a const char*, so you can just do:

const char* charArray;
std::string str(charArray);
std::string str = const_char;

Just use the std::string constructor. You can pass it a char*:

char* charArray = "My String";
std::string stdstr( charArray );

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