Accepted answer is the simplest but other ways to achieve the concatenation.
#include <iostream>
#include <string>
using namespace std;
string missingOptionArgRet(char missingArg) {
string s("Option -");
s += missingArg;
s += " requires an operand";
return s;
}
void missingOptionArgOut(char missingArg, std::string* out) {
*out = "Option -";
*out += missingArg;
*out += " requires an operand";
}
main(int, char**)
{
string s1 = missingOptionArgRet('x');
string s2;
missingOptionArgOut('x', &s2);
cout << "s1 = " << s1 << '\n';
cout << "s2 = " << s2 << '\n';
}
Using +=
rather than +
will prevent temporary string objects. Also there are 2 options. Return by value missingOptionArgRet
. This has disadvantage that as a result of return by value the string must be copied to the caller.
The second option missingOptionArgOut
can prevent this at the cost of slightly more verbose code. I pass in an already constructed string
(by pointer to make it clear its a variable to be modified, but could be passed by reference).