C++ 反复创建相同的文本文件
我需要创建一个在当前文件夹中写入文本文件的程序,该文本文件始终包含相同的信息,例如:C++ 反复创建相同的文本文件,c++,text-files,C++,Text Files,我需要创建一个在当前文件夹中写入文本文件的程序,该文本文件始终包含相同的信息,例如: Hello, This is an example of how the text file may look some information over here and here and so on 所以我想这样做: #include <iostream> #include <fstream> using namespace std; int main(){ ofstr
Hello,
This is an example of how the text file may look
some information over here
and here
and so on
所以我想这样做:
#include <iostream>
#include <fstream>
using namespace std;
int main(){
ofstream myfile("myfile.txt");
myfile << "Hello," << endl;
myfile << "This is an example of how the text file may look" << endl;
myfile << "some information over here" << endl;
myfile << "and here" << endl;
myfile << "and so on";
myfile.close();
return 0;
}
#包括
#包括
使用名称空间std;
int main(){
流myfile(“myfile.txt”);
myfile如果您不关心'\n'和std::endl之间的子文件差异,那么您可以在函数外部创建一个文本静态字符串,然后它就是:
myfile << str // Maybe << std::endl; too
myfile如果在同一文件中写入时遇到问题,则需要使用追加模式。
i、 例如,您的文件必须像这样打开
流myfile(“ABC.txt”,ios::app)
您可以在C++11中使用原始字符串:
const char* my_text =
R"(Hello,
This is an example of how the text file may look
some information over here
and here
and so on)";
int main()
{
std::ofstream myfile("myfile.txt");
myfile << my_text;
myfile.close();
return 0;
}
const char*my_text=
R“(你好,
这是文本文件的外观示例
这里有一些信息
这里呢
等等);
int main()
{
std::流myfile(“myfile.txt”);
myfile听起来你真的应该使用资源文件。我不会在这里复制和粘贴所有信息,但是这个网站上已经有一个非常好的问答,在这里:
或者,您甚至可以将字符串粘贴到头文件中,然后将该头文件包含在需要的地方:
(假设没有C++11,因为如果你这样做了,你可以简单地使用Raw使事情变得简单一点,但是已经发布了一个答案——无需重复)
#pragma一次
#包括
字符串文件数据=
“数据行1\r\n”
“数据行2\r\n”
“等。\r\n”
;
如果需要更复杂的字符,请使用std::wstring
并在字符串前面加上L
。
您所需要做的就是编写一个小脚本(如果是一次性的,甚至只需使用记事本+),将反斜杠替换为双反斜杠,将双引号替换为反斜杠双引号,并将换行符替换为\r\n“{line break}{tab}”。整理开始和结束,然后把字符串写入文件。是否必须在C++ C++中完成?如果你有一个你想要输出的模板,你可以一直读进去,然后再把它输出到正确命名的文件。文本文件而不是它?你的问题描述中一定缺少了一个重要的细节。@juanchopanza,我知道这是违反直觉的,但它是一个更大程序的一部分。听起来像是一个XY问题。你主要从哪里获得此文本资源?为什么要手工编写?使用sed或vim将输入格式化为源文件(.e.g:%s/(*)/\tmyfile
#pragma once
#include <iostream>
std::string fileData =
"data line 1\r\n"
"data line 2\r\n"
"etc.\r\n"
;