C++格式化输出,⽂本⽂件操作,⼆进制⽂件操作
1、格式化输⼊输出
以左对齐的⽅式输出整数,域宽为10;
打印有符号数和⽆符号数200;
将⼗进制整数200以0X开头的⼗六进制格式输出;
⽤前导*格式打印3.911,域宽为10
[提⽰]
可⽤ios类的成员函数或使⽤控制符来控制格式的输⼊输出。
#include
#include
#include
#include
#include
#include
#include
usingnamespacestd;
intmain()
{
cout<
inta=200;
unsignedintb=200;
cout<<"OX"<
('*');//⽤前导*格式打印3.911,域宽为10
(10);
cout<
return0;
}
运⾏结果如下:
题⽬2、⽂本⽂件操作
[任务]编写程序,打开d:⽂件,向其中写⼊11⾏字符(如下表),关闭⽂件。然后以读⽅式打开,输出⽂件内容。
voidmain()
{
ifstreaminf("e:");
chars[1000];
while(())
{
inf>>s;
cout<
}
();
}
程序如下:
#include
#include
#include
#include
#include
#include
#include
usingnamespacestd;
intmain()
{
ifstreamis("");//存储上⾯的11⾏代码
chars[1000];
inti=0;
while((s[i]=())!=EOF)//读取中的每⼀个字符并将其读取到s中
{
cout<
i++;
}
();
ofstreamos("");
(reinterpret_cast
return0;
}
运⾏结果如下:
打开所看到的内容与上图⼀样。
题⽬3、⼆进制⽂件操作
[任务]编写程序,打开d:⼆进制⽂件,向其中写⼊⼀个结构体(如下定义)数组,包括10个元素(内容⾃⾏定义)。然后再
写⼀个程序打开个这⽂件,并将⽂件内容读取取来,并显⽰到屏幕上。结构体如下:
structStudent{
charid[10]//学号
charname[20]//姓名
floatscore;//成绩
ints_class//班级
doubleheight//⾝⾼
}
#include
#include
#include
#include
#include
#include
#include
#include
usingnamespacestd;
structStudent
{
charid[10];
charname[20];
floatscore;
ints_class;
doubleheight;
};
intmain()
{
Studentstudent={"60001","KingRed_D",100,20,180};
inta[10]={7,776,767,78,76,6,7,76,788,55};
ofstreamos("",ios_ba::binary);//创建输出流对象,并以⼆进制的⽅式打开⽂件
(reinterpret_cast
(reinterpret_cast
();
ifstreamis("",ios_ba::in|ios_ba::binary);//创建输⼊流对象
if(())
{
Studentstudent1;
intb[10];
(reinterpret_cast
(reinterpret_cast
/*打印内容到屏幕上*/
cout<<"id:"<<<
cout<<"name:"<<<
cout<<"score:"<<<
cout<<"class:"<
cout<<"height:"<<<
for(inti=0;i<10;i++)
cout<
cout<
}
el
{
cerr<<"ERROR:Cannotopenfile''."<
}
();
return0;
}
运⾏结果如下:
本文发布于:2023-01-02 12:33:16,感谢您对本站的认可!
本文链接:http://www.wtabcd.cn/fanwen/fan/90/77717.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |