/*C++写入文本文件的操作和例子*/
/*写入文件中:
1、首先要创建一个ofstream的对象
2、文件的打开
3、内容的输入(与cout的用法基本一致)
4、文件的关闭*/
#include<iostream>//该文件中包含ostream类,而cout就是ostream类的对象
#include<fstream>//该文件中包含ofstream类,而该类的对象可以由用户自定义(重点)
using namespace std;
int main() {
char automobile[50];
int year;
int month;
int day;
cout << "年份:";
cin >> year;
cout << "月份:";
cin >> month;
cout << "天号数:";
cin >> day;
ofstream outFile;//创建一个输出流对象outFile
outFile.open("test.txt");//打开目标文件,该处可以使用绝对路径,也可以使用相对路径
//接下来的用法和cout一模一样
outFile <<"年份:"<< year << " ";
outFile << "月份:"<<month << " ";
outFile <<"天号数:"<< day << endl;
outFile.close();//关闭目标文件(漏写该句代码,程序会自动关闭文件)
return 0;
}
输入信息:
运行后文件中结果: