实验6 模板类和文件IO

一、实验任务三

1.源代码:

task3_1.cpp

#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("data.dat",ios::binary);
  if(!out.is_open()){

    cout<<"fail to open data1.dat\n";
    return 1;
  }
  out.write(reinterpret_cast<char *>(&x),sizeof(x));
  out.close();


}

task3_2.cpp

#include<iostream>
#include<fstream>
#include<array>
#define N 5

int main(){
  using namespace std;
  array<int,N>x;

  ifstream in;  
  in.open("data.dat",ios::binary);
  if(!in.is_open()){
    cout<<"fail to open data1.dat\n";
    return 1;
  }

  in.read(reinterpret_cast<char*>(&x),sizeof(x));
  in.close();
  
  for(auto i=0;i<N;i++)
  cout<<x[i]<<", ";
  cout<<"\b\b \n";
}

2.运行测试:

 

 当把array<int,N>x;修改为array<char,N>x后:

 

原因:char类型占用1字节,int类型占用4个字节,所以输出会显示三个空格,且b在第五个位置出现。

二、实验任务四

1.源代码:

Vector.hpp

#pragma once
using namespace std;
template <typename T>
class Vector
{
private:
    int size;
    T *p;

public:
    Vector(int n): size{n} {p = new T[n];};
    Vector(int n, T x):size{n}
    {
        p = new T[n];
        for (int i = 0; i < n; i++)
            p[i] = x;
    };
    Vector(const Vector<T> &y): size{y.size}
    {
        p = new T[size];
        for (int i = 0; i < y.size; i++)
        p[i] = y.p[i];
    };
    ~Vector()=default;
    
    int get_size() { return size; }
    T &at(int index){return p[index];}
    T &operator[](int index){return p[index];}
   
    friend void output(Vector &x)
    {
        int i;
        for (i = 0; i < x.size - 1; i++)
        {
            cout << x.p[i] << ", ";
        }
        cout << x.p[i] << endl;
    }
};

task4.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();
}

2.运行测试:

 

更换数据后:

 

三、实验任务5

1.源代码:

task5.cpp

#include<iostream>
#include<fstream>
#include<iomanip>
#include<string>
using namespace std;

void output(ostream &out){
 char a[26][26],i;
 cout<<" ";
 out<<" ";
 for(i='a';i<'z';i++)
 {
   cout<<setw(2)<<setfill(' ')<<i;
   out<<setw(2)<<setfill(' ')<<i;
 }
  cout<<endl;out<<endl;
 for(int j=0;j<26;j++)
 {
    cout<<setw(2)<<setfill(' ')<<j+1;
    out<<setw(2)<<setfill(' ')<<j+1;
     for(int n=0;n<26;n++)
     {
       a[j][n]='A'+char(j+n+1)%26;
       cout<<setw(2)<<setfill(' ')<<a[j][n];
       out<<setw(2)<<setfill(' ')<<a[j][n];
     }
     cout<<endl;out<<endl;
 }
}

int main(){
 ofstream out;
 out.open("cipher_key.txt",ios::out);
 if(!out.is_open())
{cout<<"fail to open txt!"<<endl;
return 1;
}
  output(out);
  out.close();
}

2.运行测试:

 

 

 

 

posted @ 2022-12-04 20:24  小帅不爱摆烂  阅读(18)  评论(0编辑  收藏  举报