TASK3:
#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; } // 把从地址&x开始连续sizeof(x)个字节的数据块以字节数据块方式写入文件data1.txt out.write(reinterpret_cast<char*>(&x), sizeof(x)); out.close(); }CPP1
#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关联的文件data1.dat中读取sizeof(x)字节数据写入&x开始的地址单元 in.read(reinterpret_cast<char*>(&x), sizeof(x)); in.close(); for (auto i = 0; i < N; ++i) cout << x[i] << ", "; cout << "\b\b \n"; }CPP2
改动之后结果如图所示,首先内存是连续储存的,int类型占4个字节,char类型占1个,储存就空的部分自动补零,所以一开始97,输出a,而a之后连续三个内存0,所以输出错误,第五个内存单元则储存98,输出b
TASk4:
#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(); }cpp
#pragma once #include <iostream> using namespace std; template <typename T> class Vector { public: Vector(int n) { size = n; t = new T[n]; } Vector(int n, T a) { size = n; t= new T[n]; for (int i = 0; i < n; i++) { t[i] = a; } } T& at(int n) { return t[n]; } T& operator[](int n) { return t[n]; } int getsize() { return size; } private: int size; T* t; }; template <typename T> void output(Vector<T>& t) { for (int i = 0; i < t.getsize(); i++) cout << t[i] << ' '; cout << endl; }hpp
Task5:
#include<iostream> #include <fstream> #include <iomanip> using namespace std; void output(std::ostream& out); int main() { ofstream f; f.open("cipher_key.txt"); if (!f.is_open()) { cout << "fail to open file " << "cipher_key" << endl; } output(f); f.close(); output(cout); } void output(std::ostream& out) { char code[30]; char Code[30]; for (int i = 0; i < 26; i++) { code[i] = 'a' + i; } out << " "; for (int i = 0; i < 26; i++) { out << code[i] << " "; } out << "\n"; for (int i = 1; i <= 26; i++) { for (int t = 0; t < 26; t++) { if (t + i <= 25) { Code[t] = 'A' + t + i; } else if (t + i > 25) { Code[t] = 'A' + t + i - 25 - 1; } } out << setw(2) << i << " "; for (int t = 0; t < 26; t++) { out << Code[t] << " "; } out << "\n"; } }View Code
标签:int,Vector,实验,output,include,open,out From: https://www.cnblogs.com/Xl995/p/16948195.html