Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Garbage when converting character to string using concatenation

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading