1、格式化输入输出
以左对齐的方式输出整数,域宽为10;
打印有符号数和无符号数200;
将十进制整数200以0X开头的十六进制格式输出;
用前导*格式打印3.911,域宽为10
[提示]
可用ios类的成员函数或使用控制符来控制格式的输入输出。
<span style="font-size:18px;">#include <iostream>
#include <algorithm>
#include <fstream>
#include <vector>
#include <iomanip>
#include <string>
#include <iterator>
#include <functional>
using namespace std;
int main()
{
cout << setiosflags(ios_base::left) << setw(10) << 120 << endl;//以左对齐的方式输出整数,域宽为10;
int a = 200;
unsigned int b = 200;
cout << a << "\t" << b << endl; //打印有符号数和无符号数200;
cout << "OX" << setiosflags(ios_base::hex) << hex<< 200<< endl;//将十进制整数200以0X开头的十六进制格式输出
cout.fill('*');//用前导*格式打印3.911,域宽为10
cout.width(10);
cout << resetiosflags(ios_base::left) << 3.911<< endl;
return 0;
}</span>
运行结果如下:
题目2、文本文件操作
[任务]编写程序,打开d:\test.txt文件,向其中写入11行字符(如下表),关闭文件。然后以读方式打开,输出文件内容。
void main( ) { ifstream inf("e:\\log.txt"); char s[1000]; while(inf.good()) { inf >> s; cout << s << endl; } inf.close(); } |
程序如下:
<span style="font-size:18px;">#include <iostream>
#include <algorithm>
#include <fstream>
#include <vector>
#include <iomanip>
#include <string>
#include <iterator>
#include <functional>
using namespace std;
int main()
{
ifstream is("log.txt"); //存储上面的11行代码
char s[1000];
int i = 0;
while((s[i] = is.get())!=EOF) //读取log.txt中的每一个字符并将其读取到s中
{
cout << s[i]; //打印到屏幕上
i++;
}
is.close();
ofstream os("test.txt");
os.write(reinterpret_cast<char *>(&s), i); // 写入文件test.txt中
return 0;
}
</span>
运行结果如下:
打开test.txt所看到的内容与上图一样。
题目3、二进制文件操作
[任务] 编写程序,打开d:\example.dat二进制文件,向其中写入一个结构体(如下定义)数组,包括10个元素(内容自行定义)。然后再写一个程序打开个这文件,并将文件内容读取取来,并显示到屏幕上。结构体如下:
struct Student{
char id[10] // 学号
char name[20] // 姓名
float score; // 成绩
int s_class // 班级
double height // 身高
}
#include <iostream>
#include <algorithm>
#include <fstream>
#include <vector>
#include <iomanip>
#include <string>
#include <iterator>
#include <functional>
using namespace std;
struct Student
{
char id[10];
char name[20];
float score;
int s_class;
double height;
};
int main()
{
Student student = {"60001", "KingRed_D", 100, 20, 180};
int a[10] = {7, 776, 767, 78, 76, 6, 7, 76, 788, 55};
ofstream os("example.dat", ios_base::binary); //创建输出流对象,并以二进制的方式打开文件
os.write(reinterpret_cast<char *>(&student), sizeof(student)); //写入文件
os.write(reinterpret_cast<char *> (a), sizeof(a));
os.close();
ifstream is("example.dat", ios_base::in|ios_base::binary); //创建输入流对象
if(is.good())
{
Student student1;
int b[10];
is.read(reinterpret_cast<char *>(&student1), sizeof(student1));
is.read(reinterpret_cast<char *>(b), sizeof(b));
/* 打印内容到屏幕上 */
cout << "id:" << student1.id << endl;
cout << "name:" << student1.name << endl;
cout << "score:" << student1.score << endl;
cout << "class:" << student1.s_class << endl;
cout << "height:" << student1.height << endl;
for(int i = 0; i < 10; i++)
cout << setw(5) << b[i];
cout << endl;
}
else
{
cerr << "ERROR:Cannot open file 'example.dat'." << endl;//如果文件打开失败,输出错误信息
}
is.close();
return 0;
}
运行结果如下: