第六章、输入输出流

第六章、输入输出流

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));
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值