I know this question is ancient, but it does show up at the top of Google, and it took a while for me to realize the answer. Also the fill constructor mentioned in the other answer is not intended for this. It occurred to me that since std::string
AKA std::basic_string<char>
accepts string literals which are char *
s just as a char []
does, it can accept a char
just like a char []
would.
Standard initialization of char []
with char
(s); where ch
is a variable or constant of type char
:
char chPtr[] = {ch, '\0'}; // Will continue out of bounds without terminator
std::string str = {ch}; // Wont continue out of bounds (1)
// Also: std::string str{ch}; // operator= is optional
Note 1: string
doesn't use \0
as a string terminator, instead holding it as just another character.
Also note that casting it to a char *
wont work:
std::string str = (char*)ch; // Breaks All Output
For your testing convenience: https://onlinegdb.com/sEl5BoBGx