c++appendpush-back

Why I can't use append() to add a variable to a string?


I have a piece of code:

char temp = word[0];
word.erase(0, 1);
word.append(temp);     //word.push_back(temp); is fine

I got an error: error: no matching member function for call to 'append'

My question is why I can't use append() here? Thanks in advance!


Solution

  • I am going to assume that word is a std::string.

    If you look at the documentation for std::basic_string::append(), you'll see that it has a bunch of overloads, but all of them are for strings or repeated characters. There simply is not any overload that accepts a single character.

    That's all there is to it.

    push_back() appends single characters, append() appends strings of characters. In your example, temp is a single character, so of the two function you are inquiring about, only push_back() is available.

    Alternatively, std::string provides operator+=(), which works in both cases. So you could also do:

    word += temp;