3

im getting totally confused by this seemingly simple problem.

I have a pain old char, and I want to concatenate it in the middle of a string. Like so.

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

I was guessing the + operand was smart enough to deal with this sort of trivial thing, if not, what would be the simplest way of doing this?

Tristus
  • 123
  • 1
  • 13
  • 4
    `return string("Option -") + missingArg + " requires an operand";` – Igor Tandetnik May 18 '15 at 01:34
  • cool, that seems to work, but what I dont get is that I thought "Option -" was already a string, why are we casting it to a string with "string()"? – Tristus May 18 '15 at 01:41
  • "Option -" is a `char[9]` not a `std::string` and similarly for the other string literal. Primitive types like that don't just automatically spawn complex types. That's the legacy of how this language was created. – TheUndeadFish May 18 '15 at 01:52

2 Answers2

3

To concatenate string literal and char:

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

A similar thing happens when you need to concat two strings literals.

Note that "something" is not a std::string, it is a pointer to an array of chars. Then you can't concatenate two string literals using +, that would be adding two pointers and is not what you want.

The correction of your code is in Igor's comment.

JosEduSol
  • 5,268
  • 3
  • 23
  • 31
1

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).

Paul Rooney
  • 20,879
  • 9
  • 40
  • 61