How to print the content of a string as “sting literal source”

Suppose s is

a
b
c
    const std::string s = 
    std::cout << R"( s )" << std::endl;

How to std::cout the content of the string in raw literal? I mean the cout return the value in this format: "anbnc".

I need to transform a very large text into a std::string. I cant use fileread as i need to define its value inside the src.

Answer

You can load this text file into a std::string like this:

Store the text in your file, e.g. mystring.txt, as a raw string literal in the format R"(raw_characters)":

R"(Run.M128A XmmRegisters[16];
          BYTE Reserved4[96];", Run.CONTEXT64 := "        DWORD64 P1Home;
          DWORD64 P2Home;
...
)"

#include the file into a string:

namespace
{
    const std::string mystring =
    #include "mystring.txt"
    ;
}

Your IDE might flag this up as a syntax error, but it isn’t. What you’re doing is loading the contents of file directly into the string at compile time.

Finally print the string:

std::cout << mystring << std::endl;

Why not just save the escaped version of the string in the file?


Any way, here’s a function to ‘escape’ characters:

#include <iostream>
#include <string>
#include <unordered_map>

std::string replace_all(const std::string &mystring)
{
    const std::unordered_map<char, std::string> lookup =
        { {'n', "\n"}, {'t', "\t"}, {'"', "\""} };

    std::string new_string;
    new_string.reserve(mystring.length() * 2);

    for (auto c : mystring)
    {
        auto it = lookup.find(c);
        if (it != lookup.end())
            new_string += it->second;
        else
            new_string += c;
    }

    return new_string;
}

int main() {

    std::string mystring = R"(Run.M128A XmmRegisters[16];
          BYTE Reserved4[96];", Run.CONTEXT64 := "        DWORD64 P1Home;
          DWORD64 P2Home;
          DWORD64 P3Home;
          DWORD64 P4Home;
          DWORD64 P5Home;
          DWORD64 P6Home;)";
    auto new_string = replace_all(mystring);
    std::cout << new_string << std::endl;
    
    return 0;
}

Here’s a demo.

Leave a Reply

Your email address will not be published. Required fields are marked *