amanuel2 amanuel2 - 1 month ago 11
C++ Question

How to include character literals?

I have a question on how to include string literals , when getting info from file. Let me show code for better understanding:

Program.b :

print \"Hello World\n\"; print \"Commo Estas :)\n\"; print \"Bonjour\";print \"Something\"; return 0;


main.cpp(I have minimized actual file to what is needed for this question):

int main()
{
std::string file_contents;
std::fstream file;
file.open("Program.b");
std::ifstream file_read;
file_read.open("Program.b");

if(file_read.is_open())
while(getline(file_read,file_contents));

cout << file_contents << endl;

}


So right now when i print
file_contents
, i get :

print \"Hello World\n\"; print \"Commo Estas :)\n\"; print \"Bonjour\";print \"Something\"; return 0;


You can see it include the
\n
. Is there a way to like , make that an actual character literal so when printing it actually prints a new line. Same for quotation (
"
)? Help Would Be Greatly Appreciated!

Answer

Try something like this:

Program.b

R"inp(print "Hello World\n"; print "Commo Estas :)\n"; print "Bonjour";print "Something"; return 0;)inp"

main.cpp

int main() {
    std::string file contents = 
    #include "Program.b"
    ;
    std::cout << file_contents << std::endl;

}

You can also change Program.b to make it a bit more readable:

R"inp(
print "Hello World\n"; 
print "Commo Estas :)\n"; 
print "Bonjour";
print "Something"; 
return 0;
)inp"

The runtime variant should be simply:

Program.b

print "Hello World\n"; 
print "Commo Estas :)\n"; 
print "Bonjour";
print "Something"; 
return 0;

main.cpp

int main()
{
    std::string file_contents;
    std::fstream file;
    file.open("Program.b");
    std::ifstream file_read;
    file_read.open("Program.b");

    if(file_read.is_open()) {
        std::string line;
        while(getline(file_read,line)) {
             file_contents += line + `\n`;
        }
    }

    cout << file_contents << endl;

}