I am converting a character to a string by concatenating it with an empty string (""). But it results in undefined behaviour or garbage characters in the resultant string. Why so?
char c = 'a';
string s = ""+c;
cout<<s<<" "<<s.size()<<"\n";
>Solution :
Let’s look at your snippet, one statement or a line at a time.
char c = 'a';
This is valid, assigning a character literal to a variable of type char.
Note: since c is not changed after this statement, you may want to declare the definition as const.
string s = ""+c;
Let’s refactor:
std::string s = ("" + c);
Let’s add type casting to make the point more clear:
std::string s = ((const char *) "" + (char) c);
The order of operations is resolve all expressions on the right hand side (rhs) of the assignment operator before assigning to the string variable.
There is no operator+() in C++ that takes a const char * and a single character.
The compiler is looking for this function: operator+(const char *, char).
This is the primary reason for the compilation errors.
cout<<s<<" "<<s.size()<<"\n";
The string assignment and creation failed, thus s is empty and s.size() is zero.