Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ ternary operator string concatenation

Tags:

c++

I have seen this question asked for other languages, but not C++. Here's what I'm trying to do:

bool a = true;
string s;
s.append("a:" + (a? "true" : "false"));    
cout << s << endl;

I get a compiler error stating that I cannot add two pointers. What gives?

like image 693
Gareth Avatar asked Mar 14 '14 17:03

Gareth


2 Answers

s.append(string("a:") + (a? "true" : "false"));
like image 57
keltar Avatar answered Sep 27 '22 19:09

keltar


"true", "false", "a:", "b:" and "c:" are pointers (raw char arrays, actually). When you add them together with + (e.g. "a:" + "true") , then std::string is not involved, and it's only std::string which actually gives + the meaning of concatenation.

Here's what I do in such situations:

s += "a:" + std::string(a ? "true" : "false");
like image 20
Christian Hackl Avatar answered Sep 27 '22 19:09

Christian Hackl