Reputation: 4646
I have a question on how to include string literals when getting info from a file. Let me show my 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 the 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 includes the \n
. Is there a way to make that an actual character literal, so printing it actually prints a new line? (I would want the same for quotation marks.)
Upvotes: 8
Views: 216
Reputation: 1
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;
}
Upvotes: 6
Reputation: 49028
You can do a simple find + replace.
std::size_t pos = std::string::npos;
while ((pos = file_contents.find("\\n")) != std::string::npos)
file_contents.replace(pos, 1, "\n");
//Every \n will have been replaced by actual newline character
Upvotes: 2