I have a question regarding which functions work for appending strings.
In this particular code, it asks: Given string givenInput on one line and character extension on a second line, append extension to givenInput.
Ex: If the input is:
Hello !
then the output is:
Hello!
The code I have so far
int main() {
string givenInput;
char extension;
getline(cin, givenInput);
cin >> extension;
// this is the line of code I am allowed to edit and have come up with:
givenInput.push_back(extension);
cout << givenInput << endl;
Why is it that givenInput.push_back(extension); works but then givenInput.append(extension); does not?
I thought that append() works with types such as strings, characters, integers, etc..., but when I use the append function, it gives an error...
I actually originally had givenInput = givenInput.append(extension); , but there was an error, which then led me to do just givenInput.append(extension); (which also had an error), which then finally left me to try givenInput.push_back(extension); which ended up working.
In this other prompt, it asks: Assign secretID with firstName, a space, and lastName.
Ex: If firstName is John and lastName is Doe, then output is: John Doe
I have:
int main() {
string secretID;
string firstName;
string lastName;
cin >> firstName;
cin >> lastName;
// this is the line of code I can edit
secretID = firstName.append(" " + lastName);
cout << secretID << endl;
Why in this case would the append function work, but it wouldn't work for the other example?
Is it simply due to the fact that lastName is a string, while extension is a char?
Also, why is it that something like secretID = firstName.append(); works for this second example while something like givenInput = givenInput.append(extension) does not work for the first example?
I know this is A LOT of text, but if someone could please explain the rules behind this, that would be greatly appreciated, as it would clear up my confusion!!
***Note: I do understand that something like givenInput = givenInput + extension; as well as
secretID = firstName + " " + lastName; would work for both examples, but I guess I am asking simply about the rules that apply for the append() and push_back() functions, regardless of if they aren't the most optimal to use for these cases.
In the class
std::string(or class templatestd::basic_string) there is no overloaded member functionappendthat has only one parameter of the typechar(orcharT). For characters there is the following overloaded member functionappendSo you could write for example
The set of overloaded member functions
appendis similar to the constructors of the classstd::string: in general member functionsappendhave similar lists of parameters as constructors. Consider for example the following constructorAs you can see the above function append has the same parameters as the first two parameters of the constructor.
Pay attention to that instead of this statement
you could just write