实验任务3:
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("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_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.read(reinterpret_cast<char *>(&x), sizeof(x)); in.close(); for(auto i = 0; i < N; ++i) cout << x[i] << ", "; cout << "\b\b \n"; }
当把
array<int, N> x; ----> 修改成: array<char, N> x;
原因: 当array数组储存字符型时,读入文件内容”a b c d e f“将把空格也读成字符。
实验任务4:
Vector.hpp:
#include <iostream> using namespace std; template<typename T> class Vector { public: Vector(int n) :size{ n } { p = new T[n]; } Vector(T n, T value) :size{ n } { p = new T[n]; for (auto i = 0; i < size; i++) { p[i] = value; } } Vector(Vector& vi) :size{ vi.size } { cout << "copy constructor called." << endl; p = new T[size]; for (auto i = 0; i < size; ++i) { p[i] = vi.p[i]; } } ~Vector() = default; T get_size() { return size; } T& at(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; } T & operator [](int n) { return p[n]; } private: T size; T* p; };
task:
#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(); }
实验任务5:
#include <iostream> #include<fstream> #include<string> using namespace std; void output() { string a[27][27] = { " " }; int i, j, n = 0; for (i = 1; i < 27; i++) { a[i][0] = to_string(i); a[0][i] = 97 + n; n++; } for (i = 1; i < 27; i++) { n = i; for (j = 1; j < 27; j++) { if (65 + n > 90) { a[i][j] = 65 + n - 26; } else { a[i][j] = 65 + n; } n++; } } ofstream out; out.open("cipher_ke.txt"); if (!out.is_open()) { cout << "fail to open cipher_key.txt to write" << endl; } for (i = 0; i < 27; i++) { for (j = 0; j < 27; j++) { cout << a[i][j] << " "; out << a[i][j] << " "; } cout << endl; out << endl; } } int main() { output(); }
标签:++,int,Vector,实验,include,open,out From: https://www.cnblogs.com/lovelexington/p/16938186.html