ama*_*el2 8 c++ special-characters
我有一个问题,如何从文件中获取信息时包含字符串文字.让我展示一下我的代码以便更好地理解:
Program.b:
print \"Hello World\n\"; print \"Commo Estas :)\n\"; print \"Bonjour\";print \"Something\"; return 0;
Run Code Online (Sandbox Code Playgroud)
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())
while(getline(file_read,file_contents));
cout << file_contents << endl;
}
Run Code Online (Sandbox Code Playgroud)
所以当我打印时file_contents,我得到:
print \"Hello World\n\"; print \"Commo Estas :)\n\"; print \"Bonjour\";print \"Something\"; return 0;
Run Code Online (Sandbox Code Playgroud)
你可以看到它包括\n.有没有办法让它成为一个真正的字符文字,所以打印它实际上会打印一个新行?(我希望引号一样.)
尝试这样的事情:
Program.b
R"inp(print "Hello World\n"; print "Commo Estas :)\n"; print "Bonjour";print "Something"; return 0;)inp"
Run Code Online (Sandbox Code Playgroud)
main.cpp中
int main() {
std::string file contents =
#include "Program.b"
;
std::cout << file_contents << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
您还可以更改Program.b以使其更具可读性:
R"inp(
print "Hello World\n";
print "Commo Estas :)\n";
print "Bonjour";
print "Something";
return 0;
)inp"
Run Code Online (Sandbox Code Playgroud)
运行时变体应该简单:
Program.b
print "Hello World\n";
print "Commo Estas :)\n";
print "Bonjour";
print "Something";
return 0;
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
141 次 |
| 最近记录: |