arduino ide - 将字符串和整数连接到 char

arduino ide - concatenate string and integer to char

以下代码应该适用于字符串,但似乎不适用于字符数组。

char *TableRow = "
           <div class = \"divTableRow\">
           <div class = \"divTableCell\">" + j + "< / div >
           <div class = \"divTableCell\" id=\"tm" + i + "b" + j + "\">0< / div >
           <div class = \"divTableCell\" id=\"sm" + i + "b" + j + "\">0< / div >
           < / div >
           ";

我收到消息说缺少终止 " 字符。我想要完成的是将文本和变量(int jint i)连接到 char 数组。我做错了什么?

String literals without prefix in C++ are of type const char[N]. For example "abc" is a const char[4]. Since they're arrays, you can't concatenate them just like how you don't do that with any other array types like int[]. "abc" + 1 is pointer arithmetic and not the numeric value converted to string then append to the previous string. Besides you can't have multiline strings like that. Either use multiple string literals, or use R"delim()delim"

因此,要获得这样的字符串,最简单的方法是使用 stream

std::ostringstream s;
s << R"(
    <div class = "divTableRow">
    <div class = "divTableCell">)" << j << R"(</div>
    <div class = "divTableCell" id="tm")" << i << "b" << j << R"(">0</div>
    <div class = "divTableCell" id="sm")" << i << "b" << j << R"(">0</div>
    </div>
    )";
auto ss = s.str();
const char *TableRow = ss.c_str();

您也可以将整数值转换为字符串,然后连接字符串。这是一个使用多个连续字符串文字而不是原始字符串文字的示例:

using std::literals::string_literals;

auto s = "\n"
    "<div class = \"divTableRow\">\n"
    "<div class = \"divTableCell\""s + std::to_string(j) + "</div>\n"
    "<div class = \"divTableCell\" id=\"tm" + std::to_string(i) + "b"s + std::to_string(j) + "\">0</div>\n"
    "<div class = \"divTableCell\" id=\"sm" + std::to_string(i) + "b"s + std::to_string(j) + "\">0</div>\n"
    "</div>\n"s;
const char *TableRow = s.c_str();

如果您使用的是较旧的 C++ 标准,请删除 usings 后缀