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


Question

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.

1
153
8/9/2016 8:20:19 PM

Accepted Answer

y += d;

I would use += operator instead of named functions.

197
9/24/2009 2:29:28 PM

Use push_back():

std::string y("Hello worl");
y.push_back('d')
std::cout << y;

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon