实验六 模板类和文件IO
实验任务3
1 #include <iostream> 2 #include <fstream> 3 #include <array> 4 #define N 5 5 6 int main() { 7 using namespace std; 8 9 array<int, N> x {97, 98, 99, 100, 101}; 10 11 ofstream out; 12 out.open("data1.dat", ios::binary); 13 if(!out.is_open()) { 14 cout << "fail to open data1.dat\n"; 15 return 1; 16 } 17 18 out. Write(reinterpret_cast<char *>(&x), sizeof(x)); 19 out.close(); 20 }
1 #include <iostream> 2 #include <fstream> 3 #include <array> 4 #define N 5 5 6 int main() { 7 using namespace std; 8 array<int, N> x; 9 10 ifstream in; 11 in.open("data1.dat", ios::binary); 12 if(!in.is_open()) { 13 cout << "fail to open data1.dat\n"; 14 return 1; 15 } 16 17 in.read(reinterpret_cast<char *>(&x), sizeof(x)); 18 in.close(); 19 20 for(auto i = 0; i < N; ++i) 21 cout << x[i] << ", "; 22 cout << "\b\b \n"; 23 }
对task3_2.cpp的代码稍做改动,把line8的数组类型从int类型修改成char类型,即:array<int, N> x;----> 修改成: array<char, N> x;其它不做任何改动,再次运行程序,运行结果如下:
97的ASCLL码值是a,文件里存放的x是整型,在内存占4个字节的空间,把它转换成char字符,a只占1个字节,多出来的3个字节被后面的变量读取,
实验任务4:
1 #include <iostream> 2 #include "Vector.hpp" 3 4 void test() { 5 using namespace std; 6 7 int n; 8 cin >> n; 9 10 Vector<double> x1(n); 11 for(auto i = 0; i < n; ++i) 12 x1.at(i) = i * 0.7; 13 14 output(x1); 15 16 Vector<int> x2(n, 42); 17 Vector<int> x3(x2); 18 19 output(x2); 20 output(x3); 21 22 x2.at(0) = 77; 23 output(x2); 24 25 x3[0] = 999; 26 output(x3); 27 } 28 29 int main() { 30 test(); 31 }
1 #include <iostream> 2 #include "Vector.hpp" 3 4 void test() { 5 using namespace std; 6 7 int n; 8 cin >> n; 9 10 Vector<double> x1(n); 11 for(auto i = 0; i < n; ++i) 12 x1.at(i) = i * 0.7; 13 14 output(x1); 15 16 Vector<int> x2(n, 42); 17 Vector<int> x3(x2); 18 19 output(x2); 20 output(x3); 21 22 x2.at(0) = 77; 23 output(x2); 24 25 x3[0] = 999; 26 output(x3); 27 } 28 29 int main() { 30 test(); 31 }
实验任务5:
1 #include<fstream> 2 #include<iomanip> 3 #include<iostream> 4 void output(std::ostream &out){ 5 out << " "; 6 for(auto i = 0; i < 26; i++){ 7 out << (char)('a' + i) << ' '; 8 } 9 out << std::endl; 10 11 for(auto i = 1; i <= 26; i++) 12 { 13 out.width(2); 14 out << i ; 15 for(auto j = 0; j < 26; j++) 16 { 17 out.width(2); 18 out << (char)('A' +((i+j)%26)); 19 } 20 out << std::endl; 21 } 22 23 } 24 25 int main(){ 26 using namespace std; 27 28 output(cout); 29 30 ofstream out; 31 out.open("cipher_key.txt"); 32 if(!out.is_open()){ 33 cout<<"fail to open file "<<endl; 34 } 35 output(out); 36 out. close(); 37 38 39 }