2018/5/31
1.iostream
1.在C++中作为标准库存在,在其中含有着istream(输入流)和ostream(输出流),相当于两个内置的类,同时,我们使用的cin,cout相当于类中的对象;
注:可以对<<和>>进行重载,从而实现直接输出对象名直接输出内部内容的效果
#include<iostream>//含有istream和ostream
using namespace std;
class Passage
{
private:
int p_num1, p_num2;
public:
Passage()
{
p_num1 = 0;
p_num2 = 0;
}
Passage(int num1,int num2)
{
p_num1 = num1;
p_num2 = num2;
}
//运算符重载(friend)
friend ostream &operator<<(ostream&output, const Passage&number)
{
output << "num1 is " << number.p_num1 << endl;
output << "num2 is " << number.p_num2 << endl;
return output;//返回对象
}
friend istream&operator>>(istream&input, Passage&number)
{
input >> number.p_num1 >> number.p_num2;
return input;
}
};
int main()
{
Passage p1(10, 20), p2(20, 30), p3;
cout << "Enter the value of object : " << endl;
cin >> p3;
cout << "first one\n" << p1 << endl;
cout << "second one\n" << p2 << endl;
cout << "third one\n" << p3 << endl;
system("pause");
}
2.fstream
1.在C++中作为另外一个标准库而存在
2.内部有ifstream和ofstream(相当于两个类)
<1>:ifstream:表示输入文件流,用于从文件中读取信息(只读操作)
<2>:ofstream:表示输出文件流,用于向文件中写入操作
3.open()函数
void open(const char *filename, ios::openmode mode);
注:成员第一参数为文件名,第二参数为模式选择
ios::app(追加)所有写入追加到文件的末尾
ios::ate:读取位置定位到文件的末尾
ios::in:用于读取(类为ifstream则可以忽略)
ios::out:用于写入(类为ofstream则可以忽略)
ios::trunc:如果该文件存在,则截断文件;
4.close()函数
C++文件终止后,自动关闭所有刷新流,释放所有的内存,关闭所有文件
注:
在程序的最后记得使用close(),释放内存
5.写入和读取文件
//fstream
//ifstream 读取 ios::in
//ofstream 写入 ios::out
//fstream 写入和读取 ios::in||ios::out
//默认格式可以不写
//getchar用于获取换行符号
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
char data[100];
//写模式
ofstream outfile;
outfile.open("afile.txt");
//控制台操作
cout << "Writing to the file" << endl;
cout << "enter your name" << endl;
cin.getline(data, 100);//输出100个字符以内 回车截止
outfile << data << endl;
cout << "Enter your age" << endl;
cin >> data;
cin.ignore();//忽略多余成分
outfile << data << endl;//向文件中写入
outfile.close();
//读模式
ifstream infile;
infile.open("afile.txt");
cout << "Reading" << endl;
infile >> data;
cout << data << endl;
infile >> data;
cout << data << endl;
infile.close();
system("pause");
}