I want to put this:
<script src = "Script2.js" type = "text/javascript"> < / script>
in a std::string
so I append a (\
) symbol before every double quotes ("
) to give it a literal meaning of ", instead of a string demarcation in C++ like this:
std::string jsFilesImport = "<script src = \"Script2.js\" type = \"text/javascript\"> < / script>\""
If I have a big string
with many ("
), adding (\
) for every ("
) becomes difficult. Is there a simple way to achieve this in C++?
A "string literal" is a sequence of characters from the source character set enclosed in double quotation marks (" "). String literals are used to represent a sequence of characters which, taken together, form a null-terminated string.
A string literal contains a sequence of characters or escape sequences enclosed in double quotation mark symbols. A string literal with the prefix L is a wide string literal.
The only difference is that you cannot modify string literals, whereas you can modify arrays. Functions that take a C-style string will be just as happy to accept string literals unless they modify the string (in which case your program will crash).
The easiest way is to use a raw string literal:
std::string s = R"x(<script src = "Script2.js" type = "text/javascript"> < / script>)x";
// ^^^^ ^^^
You just need to take care that the x(
)x
delimiters aren't used in the text provided inside. All other characters appearing within these delimiters are rendered as is (including newlines). x
is arbitrarily chosen, could be something(
, )something
as well.
To prevent further questions regarding this:
No, it's not possible to do1 something like
std::string s = R"resource(
#include "MyRawTextResource.txt"
)resource";
The preprocessor won't recognize the #include "MyRawTextResource.txt"
statement, because it's enclosed within a pair of double quotes ("
).
For such case consider to introduce your custom pre-build step doing the text replacement before compilation.
1)At least I wasn't able to find a workaround. Appreciate if someone proves me wrong about that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With