C++从入门到放弃之:C++ I/O流

C++ I/O

1. 主流的I/O流类

						ios
				/					\
			istream					ostream
		/		|		\  		/		|		\
istrstream	ifstream	iostream	ofstream  ostrstream

2. 格式化 I/O

  • 格式化函数(本质成员函数)
    cout.precision(...);//小数精度控制
    cout.width(...);//设置域宽,字符宽度
    cout.setf(ios::showpos);//显示正号
    cout.fill('...');//指定空白位置填充符号
  • 流控制符(本质全局函数)
    #include <iomanip>(带参数的流控制符头文件)
    cout<<setprecision(...)<<...<<endl;小数精度控制
    cout<<setw(...)<<...<<endl;//设置域宽,字符宽度
    cout<<showpos<<...<<endl;//显示正号
    cout<<setfile('...')<<...<<endl;//指定空白位置填充符号
    cout<<left<<...<<endl;//默认右对齐设置左对齐
    cout<<hex<<...<<endl;//十六进制
    cout<<showbase<<...<<endl;//显示十六进制表示

3. 字符串流

  • 头文件
    #include <strstream>//过时了
    <strstream> <ostrstream>
    #include <sstream>
  • istringstream//sscanf()
istringstream iss;
//char* buf[]="123 4.56 hello"
iss.str("123 4.56 hello");
int i = 0;
double d = 0.0;
string s;
//sscanf(buf,"%d %lf %s",&i,&d,&s);
iss >> i >> d >> s;
cout << i << d << s <<endl;
  • ostringstream//sprinf()
ostringstream oss;
int i = 321;
double d = 4.56;
string s = "hello"
//sprintf(buf,"%d %lf %s",i,d,s);
oss << i << ' ' << d << ' ' << s;
cout << oss.str() << endl;

4. 文件流

  • 头文件
    #include <fstream>
  • ofstream //fprintf()
eg://写文件流
ofstream ofs("pathname",ios::out);//ios::out缺省参数可以不加,文件不存在会自动创建
ofs << 123 << ' ' << 4.56 << ' ' << "abc" << endl;
ofs.close();//关闭文件
ifstream //类似fscanf()

eg://读文件流
ifstream ifs("pathname");
int i = 0;
double d = 0.0;
string s;
ifs >> i >> d >> s;
cout << i << "," << d<< "," << s << endl;
ifs.close();//关闭文件

5.二进制I/O

  • 写//类似fwrite()
    ostream& ostream::write(cosnt char* buffer,size_t num);
    num要写入的字节数
ofstream ofs("pathname");
char wbuf[] = "hello";
ofs.write(wbuf,sizeof(wbuf));
ofs.close();
  • 读//类似fread()
    istream& istream::read(char* buffer,streamsize num);
    num期望读到的字节数,实际读到的字节数可能会比期望读的字节数小
ifstream ifs("pathname");
char rbuf[100] = {0};
ifs.read(rbuf.sizeof(rbuf));
cout << rbuf << endl;
ifs.close();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值