Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to repair "invalid operands of types 'const char' to binary 'operator+'? [duplicate]

Possible Duplicate:
How do I concatenate multiple C++ strings on one line?

According to this a C++ std::string is concatenated by using operator+. Why then does this code

using namespace std;
string sql = "create table m_table(" + 
    "path TEXT," +
    "quality REAL," +
    "found INTEGER);"; 

cause this error?

invalid operands of types 'const char [22]' and 'const char [17]' to binary 'operator+'

like image 576
jacknad Avatar asked Oct 05 '12 18:10

jacknad


3 Answers

What chris said, but in this particular case you can do

string sql = "create table m_table("
    "path TEXT,"
    "quality REAL,"
    "found INTEGER);"; 

Which will concatenate strings at compile time.

like image 116
Michael Krelin - hacker Avatar answered Nov 14 '22 20:11

Michael Krelin - hacker


You need to explicitly convert it to a string to match the argument list:

string sql = std::string("create table m_table(") + 
"path TEXT," +
"quality REAL," +
"found INTEGER);"; 

Now the first one is a string matched up with a const char[N], which matches one of the operator+ overloads and returns a new std::string, which is used to repeat the process for the rest.

like image 28
chris Avatar answered Nov 14 '22 22:11

chris


a better way is to use std::ostringstream

#include <sstream>

const std::string myFunc(const std::string& s1, const std::string& s2)
{
  std::ostringstream os;
  os<<s1<<" "<<s2;
  return os.str();
}

The advantage is that you can use the std::ostream << operator overloads to stringify non string values too

like image 1
mohaps Avatar answered Nov 14 '22 20:11

mohaps