一遍又一遍地创建同一个文本文件
Creating the same text file over and over
我需要创建一个程序,在当前文件夹中写入一个文本文件,该文本文件总是包含相同的信息,例如:
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;
}
如果我的文本文件中的行数很小,那么它就可以工作,问题是我的文本文件有超过2000行,我不愿意为每一行提供myfile << TEXT << endl;
格式。
有没有更有效的方法来创建这个文本文件?谢谢。
如果在同一个文件中写入有问题,则需要使用追加模式。也就是说,你的文件必须像这样打开
ofstream myfile("ABC.txt",ios::app)
您可以在c++ 11中使用Raw字符串:
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;
}
生活例子
或者,您可以使用一些工具为您创建数组,如xxd -i
如果您不关心'n'和std::endl之间的细微差异,那么您可以在函数之外创建一个静态字符串,然后它只是:
myfile << str // Maybe << std::endl; too
如果你的文本非常大,你可以写一个小脚本来格式化它,比如用"n"来改变每一个换行符,等等
听起来你真的应该使用资源文件。我不会在这里复制粘贴所有的信息,但是在这个网站上已经有一个非常好的问题:在原生Windows应用程序的资源中嵌入文本文件
或者,你甚至可以将字符串放在头文件中,然后在需要的地方包含该头文件:(假设没有c++ 11,因为如果你有,你可以简单地使用Raw来使事情变得更简单,但是这个问题的答案已经发布了——不需要重复)。
#pragma once
#include <iostream>
std::string fileData =
"data line 1rn"
"data line 2rn"
"etc.rn"
;
如果需要更复杂的字符,请使用std::wstring
并在字符串前加上L
。您所需要做的就是编写一个小脚本(如果是一次性的,甚至可以使用notepad++),将反斜杠替换为双反斜杠,将双引号替换为反斜杠双引号,并将换行符替换为rn"{line break}{tab}"
。整理好开头和结尾,你就完成了。然后将字符串写入文件
- 如何格式化我的文本文件以使其不会一遍又一遍地重复同一行?
- 文本冒险游戏 - 如何区分一种项目类型与另一种项目类型以及如何构建项目类/子类
- 如何在 Win32 中用一条线连接 2 个文本框?
- ExtTextOut 文本的持续闪烁,在一段时间后,文本将恢复为默认字体
- Getline在读取文本文件时有一种奇怪的行为
- 为什么当我输入一个大数字时,输出会一遍又一遍地重复?
- 如何遍历几个每小时一次的根(.root)文件,并将它们组合成更大的每日数据.root文件?
- 遍历对象向量,并找到与从文本文件中提取的对象匹配的变量
- 我如何一遍又一遍地向用户提问,直到他们输入正确的值字段?
- c++ 一遍又一遍地对函数返回相同的检查
- 一遍又一遍地构造相同的对象
- 如何使用键盘输入和sf ::文本在SFML中添加一种文本框以显示文本字符串
- 使用 QTextCursor 选择一段文本
- 有没有办法不在 c++ 中的参数中一遍又一遍地输入相同的数据类型
- 一遍又一遍地创建同一个文本文件
- 变量不计数,即使一遍又一遍地调用函数
- 将一段文本加载到字符串向量中
- 如何避免一遍又一遍地编写相同的模板
- 一遍又一遍地传递对象的替代方法
- 一遍又一遍地验证文件时遇到问题