PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, May 13, 2022

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

 May 13, 2022     append, c++, push-back     No comments   

Issue

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;


Answered By - Frank
Answer Checked By - Pedro (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing