Yana Nugraha Yana Nugraha - 4 months ago 15
C++ Question

How to append a char to a std::string?

The following fails with the error

prog.cpp:5:13: error: invalid conversion from ‘char’ to ‘const char*’


int main()
{
char d = 'd';
std::string y("Hello worl");
y.append(d); // Line 5 - this fails
std::cout << y;
return 0;
}


I also tried, the following, which compiles but behaves randomly at runtime:

int main()
{
char d[1] = { 'd' };
std::string y("Hello worl");
y.append(d);
std::cout << y;
return 0;
}


Sorry for this dumb question, but I've searched around google, what I could see are just "char array to char ptr", "char ptr to char array", etc.

Answer
y += d;

I would use += operator instead of named functions.