微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决arduino ide - 将字符串和整数连接到字符

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

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)连接到字符数组。我做错了什么?

解决方法

String literals 在 C++ 中没有前缀是 const char[N] 类型。例如,"abc" 是一个 const char[4]。由于它们是数组,因此您不能像使用任何其他数组类型(如 int[])那样将它们连接起来。 "abc" + 1 是指针算术,而不是转换为字符串然后附加到前一个字符串的数值。此外你不能有这样的多行字符串。要么使用多个字符串文字,要么使用 raw string literals 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 后缀

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。