实验六

实验六

task 3

task 3_2.cpp

#include <iostream>
#include <fstream>
#include <array>
#define N 5
int main() {
	using namespace std;
	array<char, N> x;
	ifstream in;
	in.open("data1.dat", ios::binary);
	if (!in.is_open()) {
		cout << "fail to open data1.dat\n";
		return 1;
	}
	// 从文件流对象in关联的文件data1.dat中读取sizeof(x)字节数据写入&x开始的地址单元
	in.read(reinterpret_cast<char*>(&x), sizeof(x));
	in.close();
	for (auto i = 0; i < N; ++i)
		cout << x[i] << ", ";
	cout << "\b\b \n";
}



存储整型数组时站内存四个字节的位置,高位补零的储存,但是字符读取时与整型数组不同,故出错。

task 4

Vector.hpp

#pragma once
#include<iostream>
using namespace std;
template<typename T>
class Vector {
public:
	Vector() {};
	Vector(int n) :size{ n } {
		p = new T[size];
	}
	Vector(int n, T value) :size{ n } {
		p = new T[size];
		for (auto i = 0; i < n; i++) {
			p[i] = value;
		}
	}
	Vector(const Vector<T>& v1) : size{ v1.size }
	{
		p = new T[size];
		int i;
		for (i = 0; i < size; i++)
			p[i] = v1.p[i];
	}
	~Vector() {
		delete[] p;
	}
	T& at(int index)
	{
		if (index >= 0 && index < size)
			return p[index];
	}

	friend void output(Vector<T>& v)
	{
		int i;
		for (i = 0; i < v.size; i++)
			cout << v[i] << " ";
		cout << endl;
	}

	int get_size()const
	{
		return size;
	}
	T& operator [](int index)
	{
		if (index >= 0 && index < size)
			return p[index];
	}
private:
	int size;
	T* p;

};

task 4.cpp

#include <iostream>
#include "Vector.hpp"
void test() {
	using namespace std;
	int n;
	cin >> n;
	Vector<double> x1(n);
	for (auto i = 0; i < n; ++i)
		x1.at(i) = i * 0.7;
	output(x1);
	Vector<int> x2(n, 42);
	Vector<int> x3(x2);
	output(x2);
	output(x3);
	x2.at(0) = 77;
	output(x2);


	x3[0] = 999;
	output(x3);
}
int main() {
	test();
}

task 5

task 5.cpp

#include<iostream>
#include <fstream>
#include<iomanip>
using namespace std;
void output(ostream& out) {
	int num = 26;
	out << "  ";
	for (auto i = 'a'; i <= 'z'; i++)
	{
		out << setw(2) << i;
	}
	out << endl;
    for (int i = 1; i < 27; i++) {
        out << setw(2) << i;
        num++;
        for (int k = num; k < num + 26; k++) {
            int a = k % 26 + 65;
            out << setw(2) << char(a);
        }
        out << endl;
    }
}int main() {
    ofstream out;
    output(cout);
    out.open("cipher_key.txt");
    output(out);
    out.close();
    return 0;

}

posted @ 2022-12-05 13:28  重度电音控患者  阅读(17)  评论(0编辑  收藏  举报