实验内容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"; }
运行截图:
修改后运行截图:
原因分析:
task3_2中以字节数据块方式写入文件data1.txt, char类型一次只读取一个字节长度,int 类型占四个字符的长度,x[0]读a,x[1]--x[3]读" ",x[4]读b,所以输出如此。
实验内容4:
Vector.hpp
#include<iostream> using namespace std; template<typename T> class Vector { public: Vector(int n) { length = n; arr = new T [n]; } Vector(int n, T m) { length = n; arr = new T[n]; for (int i = 0; i < n; i++)arr[i] = m; } Vector(Vector<T>& x) { length = x.get_size(); arr = new T[length]; for (int i = 0; i < length; i++)arr[i] = x.arr[i]; } T& operator [](int n) { return arr[n]; } T& at(int n) { return arr[n]; } T get_size() { return length; } ~Vector(){} private: int length;T *arr; template<typename T1> friend void output(Vector<T1>& x); }; template<typename T1> void output (Vector<T1>& x) { for (int i = 0; i < x.get_size(); i++) cout << x.at(i) << " "; cout << '\n'; }
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(); }
运行测试截图:
实验内容五:
实验代码:
task6.cpp
#include<iostream> #include<fstream> #include<string> using namespace std; void output(std::ostream &out){ cout << " "; out<<" "; char a[26]; for (int i = 0; i < 26; i++) { a[i] = 97 + i; cout << " " << a[i]; out << " " << a[i]; } cout << endl; out << endl; int k = 0; char b[100]; for (int i = 1; i <= 26; i++) { cout << i << " "; out << i << " "; for (int j = 0; j < 26; j++) { b[k] = (a[j] - 97 + i % 26) % 26 + 65; cout << b[k] << " "; out << b[k] << " "; } cout << endl; out << endl; } } int main() { ofstream outFile("cipher_key.txt", ios::binary); output(outFile); return 0; }
运行结果:
标签:arr,int,length,Vector,实验,output,include From: https://www.cnblogs.com/akumanpower/p/16938885.html