#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(); }task3_1
#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"; }task3_2
运行结果:
修改之后运行结果:
int型数据占四个字节,char类型只占一个字节;97存在第一个字节中,其余三个字节为空,98存在第五个字节中,其余依次类推;以int类型输出,每四字节一输出,所以正常输出97,98,99,100,101;以char类型输出时,每一字节输出一次,第一个字节内存里为97,ASCAII码对应a,后三个字节为空,第五个字节98对应b,所以输出a, , , ,b
#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(); }task4.cpp
#pragma once #include<iostream> using namespace std; template <class T> class Vector{ public: Vector(int n):size{n} {p = new T[size]; } Vector(int n,T value):size{n} { p = new T[size]; for(int i = 0;i < size; i++) p[i] = value; } ~Vector() {delete []p;} Vector(Vector& obj):size{obj.size} { p = new T[size]; for(int i = 0;i < size; i++) p[i] = obj.p[i]; } T &at(int i){return p[i];} T &operator[](int i) {return p[i];} int get_size() const {return size;} private: T *p; int size; friend void output(Vector &x){ for(int i = 0; i < x.size; i++) if(i!=x.size-1) cout << x.at(i) << ","; else cout << x.at(i); cout << endl; } };Vector.hpp
运行结果:
#include<iostream> #include<fstream> #include<iomanip> using namespace std; void output(ostream &out){ for(int i = 0;i <= 26; i++){ if(i==0) out << " "; else out << setw(2) << i; for(int j = 0; j < 26; j++){ if(i==0){ out << " " << (char)('a'+j); } else{ if('A'+i+j<='Z') out << " " << (char)('A'+i+j); else out << " " << (char)('A'+i+j-26); } } out << endl; } } int main(){ ofstream out; output(cout); out.open("cipher_key.txt"); if(!out.is_open()) cout << "error!\n"; output(out); out.close(); return 0; }task5.cpp
运行结果:
标签:文件,字节,int,Vector,实验,output,include,模板,size From: https://www.cnblogs.com/xrzjjy/p/16941543.html