task3:
3.1代码:
#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; } out.write(reinterpret_cast<char *>(&x), sizeof(x)); out.close(); }
3.2代码:
#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.read(reinterpret_cast<char *>(&x), sizeof(x)); in.close(); for(auto i = 0; i < N; ++i) cout << x[i] << ", "; cout << "\b\b \n"; }
运行截图 :
改为char 运行截图:
分析:int占4个空间,char只占1个空间。存入时97存入1号空间,2到4号空间存0;98存入5号空间;读取时对应1号和5号读取ASCII码为a,b;0为不显示字符。
task4:
Vector.hpp:
#include<iostream> using namespace std; template<typename T> class Vector{ public: Vector<T>(int n):size(n){a=new T[n];} Vector<T>(int n,int value):size(n){a=new T[n];for(int i=0;i<n;i++) a[i]=value;} Vector<T>(T& v):size(v.size){a=new T[size];for(int i=0;i<size;i++) a[i]=v.a[i];} ~Vector()=default; int get_size(){return size; } T& at(int i){return a[i]; } T& operator [](int i){return a[i];} friend void output(Vector<T> v) { for(int i=0;i<v.get_size();i++) cout<<v.a[i]<<" "; cout<<endl; } private: T* a; int size; };
运行截图:
task5:
代码:
#include<iostream> #include<fstream> using namespace std; void output(ofstream& out) { cout<<" "; out<<" "; for(int i=0;i<26;i++) { char ch='a'+i; cout<<ch<<" "; out<<ch<<" "; } cout<<endl; out<<endl; for(int i=0;i<26;i++) { if(i+1<10){ cout<<" "<<i+1<<" "; out<<" "<<i+1<<" ";} else{ cout<<""<<i+1<<" "; out<<""<<i+1<<" "; } for(int j=i;j<i+26;j++) { char ch='A'+j%26; cout<<ch<<" "; out<<ch<<" "; } cout<<endl; out<<endl; } } int main() { ofstream out; out.open("cipher_key.txt", ios::out); output(out); }
截图:
标签:cout,int,open,实验,include,out,size From: https://www.cnblogs.com/202183290359gyk/p/16962100.html