0
#include <iostream>
#include <conio.h>
#include <stack>
#include <string>
using namespace std;

int main{
    string h = "";
    h = ("" + 'a');
    cout << h;

    return 0;
}

Output: "nity\VC\Tools\MSVC\14.29.30133\include\xstring" I am honestly clueless as to what to do. I've never had this happen before.

Note: I've found a way to avoid this by appending the char like this:

string g="";
g+='a';

Regardless, why is this?

  • *Regardless, why is this?* -- `h = ("" + 'a');` -- This looks totally weird to a C++ programmer, however may not look weird to a JavaScript (or similar language) programmer. Did you get the idea to do this from something like JavaScript? What you are actually doing with that line of code has nothing to do with strings, and everything to do with taking a pointer and pointing it to who-knows-where. – PaulMcKenzie Jun 17 '22 at 07:51

1 Answers1

0

"" is a literal of type const char[1], which is the identical as const char* in most regards. 'a' is a literal of type char, which is really just an integer type. So if you do "" + 'a', you will get a pointer to 'a' (=97 in ASCII) characters after wherever the compiler decides to put the "". Which is then converted to an std::string.

In the working example, you convert the "" literal to std::string first, then add a char to it. std::string overloads the + and += operators, so it will produce a reasonable result.

SteakOverflow
  • 1,953
  • 13
  • 26