[英]arduino ide - concatenate string and integer to char
以下代碼應該適用於字符串,但似乎不適用於 char arrays。
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 j
和int i
)連接到 char 數組。我做錯了什么?
C++ 中沒有前綴的字符串文字屬於const char[N]
類型。 例如"abc"
是一個const char[4]
。 由於它們是 arrays,因此您不能像使用任何其他數組類型(如int[]
那樣連接它們。 "abc" + 1
是指針運算,而不是轉換為字符串的數值,然后將 append 轉換為前一個字符串。 此外,您不能擁有這樣的多行字符串。 要么使用多個字符串文字,要么使用原始字符串文字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();
您還可以將 integer 值轉換為字符串,然后連接字符串。 這是一個使用多個連續字符串文字而不是原始字符串文字的示例:
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++ 標准,請刪除using
和s
后綴
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.