【问题标题】:building a long string to be passed to function as argument构建一个长字符串作为参数传递给函数
【发布时间】:2017-05-03 11:05:56
【问题描述】:

我对 C++ 编程非常陌生,我有

char INSERT_SQL[60];

及以后的代码

  INSERT_SQL = "INSERT INTO 'tempLog' ('temperature', 'humidity') VALUES ('";
  INSERT_SQL.concat(tempInC);
  INSERT_SQL.concat("','");
  INSERT_SQL.concat(humidity);
  INSERT_SQL.concat("');");

温度和湿度值更新后。

但我收到错误提示 invalid array assignment

如果我使用String INSERT_SQL; 而不是Char INSERT_SQL[60];,则会收到此错误:

没有匹配函数调用'Connector::cmd_query(String&)'

我应该如何构建一个将不同变量连接在一起的长数组?

【问题讨论】:

    标签: c++ arrays string char concat


    【解决方案1】:

    std::strings 的设计相当糟糕,而且很难构建。

    但是你有旧的 C 函数 sprintf。这需要参数并且非常灵活,并且提供了一种构建复杂字符串(例如 sql 查询)的简单方法。构建字符串后(无论您选择哪种方法)打印出来以检查它是否正确。

    然后您可以将字符数组字符串转换为 std:;string 以进行传递。 std::strings 对此有好处。

    代码如下所示

      char query[1024];   // give yourself plenty of space;
    
      int tempInC;   // I'm guessing these will in fact be integers, not strings
      int humidity; 
      sprintf(query, "\"INSERT INTO 'tempLog' ('temperature', 'humidity') 
              VALUES(' %d, %d);\n\"", tempInC, humidity);
    
       printf("%s\n", query); // take a look, is the string right?
    
       // this interface takes a plain char *
       Connector::cmd_query(query);
    
       // you can just assign to a std string if you want to keep the query
       //  string hanging about. std::strings are better than char buffers for
       // medium-length persistent strings.
    
       std::string savequery = query;
    

    【讨论】:

      【解决方案2】:

      看起来您确实在编写 C++(根据 Connector::cmd_query(String&))。因此,您可以使用std::string

      std::string INSERT_SQL;
      /* later */
      INSERT_SQL = "INSERT INTO 'tempLog' ('temperature', 'humidity') VALUES ('";
      INSERT_SQL += tempInC;
      INSERT_SQL += "','";
      INSERT_SQL += humidity;
      INSERT_SQL += "');";
      

      只要函数调用需要const char*,就使用INSERT_SQL.c_str()

      【讨论】:

      • 谢谢它的工作原理,但它会导致不正确的 mysql 字符串
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-13
      • 2012-05-25
      • 1970-01-01
      • 2020-12-19
      • 2017-04-25
      相关资源
      最近更新 更多