Jam*_*son 100
一种方法是创建ofstream类的实例,并使用它来写入您的文件.这是一个包含一些示例代码的网站的链接,以及有关大多数C++实现可用的标准工具的更多信息:
为了完整起见,这里有一些示例代码:
// using ofstream constructors.
#include <iostream>
#include <fstream>
std::ofstream outfile ("test.txt");
outfile << "my text here!" << std::endl;
outfile.close();
Run Code Online (Sandbox Code Playgroud)
您想使用std :: endl来结束您的行.另一种方法是使用'\n'字符.这两个东西是不同的,std :: endl刷新缓冲区并立即写入输出,而'\n'允许outfile将所有输出放入缓冲区,并可能稍后写入.
Fre*_*ios 17
使用文件流执行此操作.关闭a时std::ofstream,将创建该文件.我个人喜欢以下代码,因为OP只要求创建一个文件,而不是写入它:
#include <fstream>
int main()
{
std::ofstream file { "Hello.txt" };
// Hello.txt has been created here
}
Run Code Online (Sandbox Code Playgroud)
临时变量file在创建后立即销毁,因此关闭流,从而创建文件.
Sea*_*ght 11
#include <iostream>
#include <fstream>
int main() {
std::ofstream o("Hello.txt");
o << "Hello, World\n" << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)