#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ofstream outFile; //声明ofstream 类型的变量
string s_name;
int i_age;
cout << "Please Enter your name :" << endl;
getline(cin,s_name);
cout << "Good , Please go on enter your age : " << endl;
cin >> i_age;
cout << "Your Name is " << s_name << endl;
cout << "Your Age is " << i_age << endl;
outFile.open("out.txt"); //打开文件
outFile << "Your Name is " << s_name << endl;
outFile << "Your Age is " << i_age << endl;
}
#include <fstream>
#include <string>
using namespace std;
int main()
{
ofstream outFile; //声明ofstream 类型的变量
string s_name;
int i_age;
cout << "Please Enter your name :" << endl;
getline(cin,s_name);
cout << "Good , Please go on enter your age : " << endl;
cin >> i_age;
cout << "Your Name is " << s_name << endl;
cout << "Your Age is " << i_age << endl;
outFile.open("out.txt"); //打开文件
outFile << "Your Name is " << s_name << endl;
outFile << "Your Age is " << i_age << endl;
}
//代码详解
在C++中,有一个stream这个类,所有的I/O都以这个“流”类为基础的,包括我们要认识的文件I/O,stream这个类有两个重要的运算符:
1、插入器(<<)(即输出)
向流输出数据。比如说系统有一个默认的标准输出流(cout),一般情况下就是指的显示器,所以,cout<<”HelloWorld”<<’\n’;就表示把字符串”HelloWorld”和换行字符(‘\n’)输出到标准输出流。
2、析取器(>>)(即输入)
从流中输入数据。比如说系统有一个默认的标准输入流(cin),一般情况下就是指的键盘,所以,cin>>x;就表示从标准输入流中读取一个指定类型(即变量x的类型)的数据。
要输出内容至文件中,需声明一个ofstream 类型的变量(ofstream已在fstream中定义,只需要引入头文件使用即可),然后通过ofstream outFile(定义的ofstream变量,变量名随便只要自己知道即可)调用open方法,打开指定文件,如果文件不存在则自动创建它,之后便可以像使用cout一样来使用outFile变量 ,用法和cout一致