1.采用预定义的输入输出操纵符格式控制改造12.2.2中第一题,使其达到相同的输出效果。(接1)
#include<iostream>
#include<iomanip>
using namespace std;
void showflags(long f)
{
long i = 0x8000;
for (; i; i = i >> 1)
{
if (i & f)
cout << "1";
else
cout << "0";
}
cout << endl;
}
void main()
{
cout << "----------------------------" << endl;
cout << "* * * x_width=10,x_fill= ,x_precision=4 * * *" << endl;
cout << setw(10) << setprecision(4) << 123 << " " << 123.45678 << " " << 234.567 << endl;
}
2.定义一复数类CComplex(类中含有实部real和虚部imag私有成员变量,都为double类型),重载输入运算符>>和输出运算符<<,使得该类可以直接通过输入输出运算符进行输入输出操作。
#include <iostream>
using namespace std;
class CComplex //定义复数类
{
public:
CComplex(double r = 0.0, double i = 0.0) //构造函数
{
real = r;
imag = i;
}
friend istream& operator >> (istream& in, CComplex & z); //友元重载输入
friend ostream& operator << (ostream& out, const CComplex& z); //友元重载输出
private:
double real,imag;
};
istream& operator >> (istream& cin, CComplex& c) //实现重载输入
{
cout << "请分别输入复数的实部和虚部:" << endl;
cin >> c.real>>c.imag;
return cin;
}
ostream& operator << (ostream& cout, const CComplex & c) //实现重载输出
{
if (c.imag > 0) //虚部大于0时,输出为复数类,且有加号
{
cout <<"您输入的复数是:"<< c.real;
cout <<"+"<< c.imag << "i";
return cout;
}
else if (c.imag < 0) //虚部小于0时,输出为复数类,没有加号
{
cout <<"您输入的复数是:"<< c.real;
cout << c.imag<< "i" ;
return cout;
}
else if (c.imag == 0) //虚部为0时,直接输出实部
{
cout <<"您输入的数是:"<< c.real;
return cout;
}
}
void C()
{
CComplex c1;
std::cin >> c1;
std::cout << c1;
}
int main() //主函数
{
C();
return 0;
}
3.有一名为test.txt的文件,里面分两行分别存储了整数12345678和字符串abcdefg,设计两个完整的程序,第一个程序以文本文件的方式存取该文件,第二个程序以二进制的方式存取该文件,并比较以这两种方式存取该文件对文件本身有什么影响。
文本文件:
#include<iostream>
#include<fstream>
#include<stdlib.h>
using namespace std;
void input()
{
int m = 12345678;
char n[8]="abcdefg";
ofstream file;
file.open("test.txt");//文件默认在工程目录文件夹下
file << m << endl << n;
file.close();
system("PAUSE");
}
void output()
{
char buffer[100];
ifstream file("test.txt");
while (!file.eof())//当到达文本末返回true
{
file.getline(buffer, 100);
cout << buffer << endl;
}
system("PAUSE");
}
int main()
{
input();
output();
}
二进制文件:
#include <iostream>
#include <fstream>
using namespace std;
void input()
{
char m[] = "12345678";
char n[] = "abcdefg";
ofstream file;
file.open("test.txt", ios::binary); //> _path means path of files
if (file.is_open())
{
file.write((const char*)&m, 8);
file.write("\n", 1);
file.write((const char*)&n,8); //> out put from _img to _path
}
file.close();
}
void output()
{
const char* filename = "test.txt";
char* buffer;
long size;
ifstream file(filename, ios::in | ios::binary | ios::ate);//binary 二进制操作文件
size = file.tellg();//用于输入流,返回流中‘get’指针当前的位置
file.seekg(0, ios::beg);
buffer = new char[size];
file.read(buffer, size);
cout << buffer << endl;
file.close();
delete[] buffer;
}
int main()
{
input();
output();
return 0;
}