第六章、输入输出流
1.1、输入输出流类
类名 | 作用 | 在哪个头文件中声明 |
---|---|---|
ios | 抽象基类 | iostream |
istream ostream iostream | 通用输入流和其他输入流的基类 通用输出流和其他输出流的基类 通用输入输出流和其他输入输出流的基类 | iostream |
ifstream ofstream fstream | 输入文件流 输出文件流 输入输出文件流 | fstream |
istrstream ostrstream strstream | 输入字符串流 输出字符串流 输入输出字符串流 | strstream |
1.2、输出流与格式控制
一、输出流常用函数
(1)运算符重载函数"<<"
(2)输出单个字符到屏幕或文件:
ostream &put(char ch)
(3)输出字符快信息到屏幕或文件
ostream &write(const char* pch,int nCount)
#include<iostream>
using namespace std;
int main(){
char buff[11]="0123456789";
cout<<buff<<endl;
for(int i=0;i<10;i++){
cout.put(buff[i]);
}
cout<<endl;
cout.write(buff,10);
cout<<endl;
return 0;
}
二、格式控制
头文件:#include<iomanip>
setw(n)//字段宽度
setprecision(n)//精度,有效数字
dec/hex/oct/setbase(n)//以十进制/十六进制/八进制/n进制(n只能为10,16,8)
setiosflags(ios::right)//右对齐
cout<<setiosflags(ios::fixed)<<setprecision(3)<<pi<<endl;//小数点后保留三位
=cout<<fixed<<setprecision(3)<<pi<<endl;
setfill(c)//设置填充字符
string p="www";
cout<<setfill('*')<<setw(10)<<p<<endl;
输出:*******www
setiosflags(ios::scientific)//按指数形式输出
1.3、输入流
一、get
char c,s[15];
c=cin.get();=cin.get(c);
cin.get(s,10);
从流中提取字符,包括空格
cin.get(字符数组,字符个数,终止字符)
从流中读取n-1个字符赋值到字符数组中,如果在读取完n-1个字符之前遇到指定终止字符,则提前结束读取
二、getline
char s[15];
cin.getline(s,10);//输入九位字符串
从流中提取一行字符,包括空格
cin.getline(字符数组,字符个数,终止字符)
从流中读取n-1个字符赋值到字符数组中,如果在读取完n-1个字符之前遇到指定终止字符,则提前结束读取
1.4、文本文件的输入输出
一、定义对象
ifstream file;//定义输入文件流类的对象file
ofstream file;//定义输出文件流类的对象file
fstream file;//定义输入输出文件流类的对象file
二、调用成员函数open打开文件
file.open(磁盘文件名,输入输出方式);
ofstream outfile;
outfile.open("f.dat",ios::out);//调用输出文件流成员函数open打开文件f.dat,并指定它为输出文件
方式 | 作用 |
---|---|
ios::in | 以输入方式打开文件 |
ios::out | 以输出方式打开文件,如果文件已存在,则将其原有内容全部清楚 |
三、关闭文件
outfile.close();
四、例
ifstream in;
in.open("file.txt",ios::in);
in>>name>>num;
in.close();
ofstream out;
out.open("outfile.txt",ios::out);
out<<name<<num<<endl;
out.close();
1.5、二进制文件的输入输出
一、输出
fstream out;
out.open("cord.bin",ios::out|ios::binary);
char name[10];
float s;
out.write(name,10*sizeof(char));
out.write((char *)&s,sizeof(float));
二、输入
fstream in;
in.open("cord.bin",ios::in|ios::binary);
char name[10];
float s;
in.read(name,10*sizeof(char));
in.read((char *)&s,sizeof(float));