Concatenate plain char and string?

im completely confused about this seemingly simple problem.

I have the pain of an old char and I want to concatenate it in the middle of a string. Thus.

string missingOptionArg(char missingArg) {
     return "Option -" + missingArg + " requires an operand";
}

      

I assumed the + operand was smart enough to handle such a trivial thing, if not, what would be the easiest way to do it?

+3


source to share


2 answers


To concatenate a string literal and a char:

std::string miString = std::string("something") + c;

      

A similar situation happens when you need to concatenate literals of two strings.



Note that "something"

it is not std::string

, it is a pointer to a character array. Then you cannot concatenate two string literals with +, which will add two pointers and not what you want.

Correction of the code in Igor's comment.

+3


source


The accepted answer is the simplest but different ways to achieve 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 +

prevent temporary string objects. There are also 2 options. Return by value missingOptionArgRet

. This has the disadvantage that as a result of returning by value, the string must be copied to the caller.

The second option missingOptionArgOut

can prevent this with slightly more verbose code. I am passing the already built one string

(by pointer so that it clears its variable, which needs to be modified, but can be passed by reference).

+1


source







All Articles