0

The following code should work for strings, but does not seem to be working for 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 >
           ";

I get the message that there is a missing terminating " character. What I am trying to accomplish is to concatenate the text and the variables (int j and int i) to the char array. What am I doing wrong?

phuclv
  • 37,963
  • 15
  • 156
  • 475
sharkyenergy
  • 3,842
  • 10
  • 46
  • 97

1 Answers1

1

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 raw string literals R"delim()delim"

So to get the string like that the easiest way is to use a 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();

You can also convert the integer value to string then concat the strings. Here's an example using multiple consecutive string literals instead of raw string literal:

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();

Remove using and the s suffix if you're an older C++ standard

phuclv
  • 37,963
  • 15
  • 156
  • 475
  • thank you! where do I have to tipe std::ostringstream s;? i tried various locations but get `aggregate 'std::ostringstream s' has incomplete type and cannot be defined` – sharkyenergy Jun 16 '21 at 09:38
  • @sharkyenergy you need to `#include ` – phuclv Jun 16 '21 at 09:41
  • thank you, one more thing, ss is not declared.. i tried to declare it as string but that fails... what type is `ss`? – sharkyenergy Jun 16 '21 at 09:52
  • it's `std::string`. You can check that easily in the IDE or in any C++ documentation like the link above. Or just use `auto` like I use – phuclv Jun 16 '21 at 10:00