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

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

我正在尝试创建具有可变列数的 table。 YH(i, Y1, Y2 ....Yd)

所以我在查询中创建了一个 for 循环。但它显示以下错误 -

  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 ";}

主要代码如下 -

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;
}

我尝试了以下 -

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 其中似乎有效。

您不能使用 + 将整数连接到字符串。当你写

", Y" + l

它将 l 添加到指向字符串文字的指针,并且只是 returns 另一个指针。然后,当您执行 + " real" 时,它会尝试将指针添加到该数组,但是 + 运算符没有这样的重载。 + 仅当至少一个参数是 std::string.

时才能用于连接

std::string(l) 也不行。这不是您获得数字的字符串表示形式的方式。你想要的功能是 std::to_string(l).

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

C++11 之前的替代方法:

Documentation on std::ostringstream

简而言之,ostringstream 允许您的程序写入一个自动调整大小的缓冲区,该缓冲区可以轻松转换为 string,就像您写入任何其他任何输入流的方式一样。比如cout

// create the ostringstream around the initial string data
ostringstream commandline("CREATE TABLE YH (i int primary key ");
for(int l=1;l<=d;l++) {
    // write into the ostringstream. l will automatically be converted from a number
    commandline << ", Y" << l <<" real ";
}
commandline << " ) ";

// (str() gets the string from the ostringstream. 
// c_str() converts this string into a character array
if(SQL_SUCCESS != SQLExecDirect(hdlStmt, (SQLCHAR*)(commandline.str().c_str()), SQL_NTS))
{
    cout<<"The create table sql command hasn't been executed successfully."<<endl;
}