代码之家  ›  专栏  ›  技术社区  ›  T Amin

错误:const char*和const char[7]类型的操作数对二进制运算符无效+

  •  2
  • T Amin  · 技术社区  · 7 年前

    我试图创建一个列数可变的表。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;
    }
    

    对于(int l=1;l<=d;l++){commandline+=“,Y”l“real”;}

    他们似乎都没有工作。

    2 回复  |  直到 7 年前
        1
  •  1
  •   Barmar    7 年前

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

    ", Y" + l
    

    l + " real" 它试图将指针添加到该数组,但对于 + + 仅当至少一个参数是 std::string .

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

    commandline += ", Y" + std::to_string(l) + " real ";
    
        2
  •  0
  •   user4581301    7 年前

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