实验六
task3
#include <iostream> #include <fstream> #include <array> #define N 5 int main() { using namespace std; array<int, N> x{ 97, 98, 99, 100, 101 }; ofstream out; out.open("data1.dat", ios::binary); if (!out.is_open()) { cout << "fail to open data1.dat\n"; return 1; } //把从地址&x开始连续sizeof(x)个字节的数据块以字节数据块方式写入文件data1.txt out.write(reinterpret_cast<char*>(&x), sizeof(x)); out.close(); }
#include <iostream> #include <fstream> #include <array> #define N 5 int main() { using namespace std; array<int, 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"; }
task4
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; };
.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(); }
task5
#include<bits/stdc++.h> #include<iomanip> using namespace std; void output(ofstream &out){ out.open("cipher_key.txt",ios::app); if(!out.is_open()){ cout<<"fail to open cipher_key.txt"<<endl; } for(int i=0;i<=26;i++){ if(i==0){ cout<<" "; out<<setw(2)<<left<<" "; }else{ cout<<setw(3)<<left<<i; out<<setw(3)<<left<<i; } for(int j=65;j<=90;j++){ if(i==0){ char x=j+32; cout<<setw(2)<<left<<x; out<<setw(2)<<left<<x; }else{ char x=(i+j-65)%26+65; cout<<setw(2)<<left<<x; out<<setw(2)<<left<<x; } } cout<<endl; out<<endl; } out.close(); } int main(){ ofstream out; output(out); return 0; }