1

Straight into business: I have code looking roughly like this:

char* assemble(int param)
{
    char* result = "Foo" << doSomething(param) << "bar";
    return result;
}

Now what I get is:

error: invalid operands of types ‘const char [4]’ and ‘char*’ to binary ‘operator<<’

Edit: doSomething returns a char*.

So, how do I concatenate these two?

Additional info:
Compiler: g++ 4.4.5 on GNU/Linux 2.6.32-5-amd64

1
  • Note that << groups left-to-right, not right-to-left. So when you've seen std::cout << a << b << c, that doesn't mean "concatenate a, b and c and write the result to std::cout", and << is not a concatenation operator. It means (((std::cout << a) << b) << c), that is "write each in turn of a, b and c to std::cout". operator<< for streams returns the stream itself, precisely in order to support this chaining. Commented Mar 14, 2012 at 11:32

3 Answers 3

3

Well, you're using C++, so you should be using std::stringstream:

std::string assemble(int param)
{
    std::stringstream ss;
    ss << "Foo" << doSomething(param) << "bar";
    return ss.str();
}; // eo assemble
Sign up to request clarification or add additional context in comments.

Comments

2

"Foo" and "Bar" are literals, they don't have the insertion (<<) operator.

you instead need to use std::string if you want to do basic concatenation:

std::string assemble(int param)
{
    std::string s = "Foo";
    s += doSomething(param); //assumes doSomething returns char* or std::string
    s += "bar";
    return s;
}

1 Comment

This is undefined behavior, you are returning a reference to a temporary. The string will be destroyed immediately after the return statement and you will be left with a dangling reference
1

"Foo" and "bar" have type char const[4]. From the error message, I gather that the expression doSomething(param) has type char* (which is suspicious—it's really exceptional to have a case where a function can reasonably return a char*). None of these types support <<.

You're dealing here with C style strings, which don't support concatenation (at least not reasonably). In C++, the concatenation operator on strings is +, not <<, and you need C++ strings for it to work:

std::string result = std::string( "Foo" ) + doSomething( param ) + "bar";

(Once the first argument is an std::string, implicit conversions will spring into effect to convert the others.)

But I'd look at that doSomething function. There's something wrong with a function which returns char*.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.