【问题标题】:arduino ide - concatenate string and integer to chararduino ide - 将字符串和整数连接到 char
【发布时间】:2021-09-01 00:37:05
【问题描述】:

以下代码应该适用于字符串,但似乎不适用于 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 数组。我做错了什么?

【问题讨论】:

    标签: c++ string char integer concatenation


    【解决方案1】:

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

    【讨论】:

    • 谢谢!我必须在哪里提示 std::ostringstream s;?我尝试了不同的位置,但得到aggregate 'std::ostringstream s' has incomplete type and cannot be defined
    • @sharkyenergy 你需要#include &lt;sstream&gt;
    • 谢谢,还有一件事,ss 没有被声明..我试图将它声明为字符串,但是失败了......ss 是什么类型?
    • 它是std::string。您可以在 IDE 或任何 C++ 文档(如上面的链接)中轻松检查。或者像我一样使用auto
    猜你喜欢
    • 2015-10-27
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 2023-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多