Search code examples
c++sqlfor-loopcreate-tablevertica

Error: invalid operands of types ‘const char*’ and ‘const char [7]’ to binary ‘operator+’


I am trying to create a table with variable number of columns. YH(i, Y1, Y2 ....Yd)

So I created a for loop inside the query. But it is showing the following error -

  error: invalid operands of types ‘const char*’ and ‘const char [7]’ to
  binary ‘operator+’
     for(int l=1;l<=d;l++) {commandline+=", Y"+ l +" real ";}

The main code is given below -

string commandline;
commandline = "DROP TABLE YH";
if(SQL_SUCCESS != SQLExecDirect(hdlStmt, (SQLCHAR*)(commandline.c_str()), SQL_NTS))
{
    cout<<"The drop YH table is unsuccessful."<<endl;
}

commandline = "CREATE TABLE YH"
        "(i int primary key ";
for(int l=1;l<=d;l++) {
    commandline+=", Y"+l+" real ";
}
commandline+=" ) ";
if(SQL_SUCCESS != SQLExecDirect(hdlStmt, (SQLCHAR*)(commandline.c_str()), SQL_NTS))
{
    cout<<"The create table sql command hasn't been executed successfully."<<endl;
}

I tried the following -

for(int l=1;l<=d;l++) {commandline+=", Y" l " real ";}

for(int l=1;l<=d;l++) {commandline+=", Y"+std::string(l)+" real ";}

None of them seems to be working.


Solution

  • You can't use + to concatenate an integer to a string. When you write

    ", Y" + l
    

    it adds l to the pointer to the string literal, and that just returns another pointer. Then when you do + " real" it tries to add the pointer to that array, but there's no such overload for the + operator. + can only be used for concatenation when at least one of the arguments is a std::string.

    std::string(l) doesn't work, either. That's not how you get the string representation of a number. The function you want is std::to_string(l).

    commandline += ", Y" + std::to_string(l) + " real ";