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<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"; }
问题:存储时用int类型,占四个字节,读取时按char一个字节读,97的四个字节赋值给char变量,隐式转换为a,后面的三个字节为空,接着赋值97,转换为b
task4.hpp
#pragma once #include <iostream> using namespace std; template <typename T> class Vector { public: Vector(int n) { this->size = n; v = new T[n]; } Vector(int n, T t) { this->size = n; v = new T[n]; for (int i = 0; i < n; i++) { this->v[i] = t; } } T &at(int n) { return this->v[n]; } T &operator[](int n) { return this->v[n]; } int getsize() { return this->size; } private: int size; T *v; }; template <typename T> void output(Vector<T> &v) { for (int i = 0; i < v.getsize(); i++) cout << v[i] << ' '; puts(""); }
task5.cpp
#include <iostream> #include <fstream> #include <iomanip> using namespace std; void output(std::ostream &out) { char cipher[100][100]; cipher[0][0] = ' '; for (int i = 1; i <= 26; i++) cipher[0][i] = 'a' + i - 1; for (int i = 1; i <= 26; i++) { cipher[i][0] = '0' + i; for (int j = 1; j <= 26 - i; j++) { cipher[i][j] = 'A' + i + j - 1; } for (int k = 26 - i + 1, m = 0; k <= 26; k++, m++) { cipher[i][k] = 'A' + m; } } for (int i = 0; i <= 26; i++) { if (i != 0) cout << setw(2) << cipher[i][0] - '0'; else cout << setw(2) << cipher[i][0]; for (int j = 1; j <= 26; j++) cout << setw(2) << cipher[i][j]; puts(""); } for (int i = 0; i <= 26; i++) { if (i != 0) out << setw(2) << cipher[i][0] - '0'; else out << setw(2) << cipher[i][0]; for (int j = 1; j <= 26; j++) out << setw(2) << cipher[i][j]; out << '\n'; } } int main() { ofstream out; out.open("cipher_key.txt", ios::out); if (!out.is_open()) { cout << "fail!!" << endl; return 1; } output(out); return 0; }
cipher_key.txt
标签:std,文件,cout,int,size,实验,include,模板,out From: https://www.cnblogs.com/cytxxx/p/16940969.html