#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(); }
#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"; }
将代码中的array<int,N> x 改为array<char,N> x 后,运行结果为:
将int改为char后,输入a b c d e,会将空格也读进去,又因为int类型的数据占四个字符,对编译器来说输入的其实是a,空格,空格,空格,b
所以输出结果才会改变。
#include <iostream> using namespace std; template<typename T> class Vector { public: Vector(int n):size{n} {p = new T[n];} Vector(int n,T value):size{n}{ p = new T[n]; for(auto i=0;i<size;i++) p[i]=value; } Vector(const Vector<T>&a):size{a.size}{ p=new T[size]; for(auto i=0;i<size;i++) p[i]=a.p[i]; } template<typename T1> friend void output(const Vector<T1>&a); T get_size()const{ return size; } T& at(int index){ return p[index]; } T& operator[](int i){ return p[i]; } private: int size; T *p; }; template<typename T1> void output(const Vector<T1>&a){ for(auto i=0;i<a.size;i++) cout<<a.p[i]<<", "; cout<<"\b\b \n"; }
#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(); }
#include<iostream> #include<iomanip> #include<fstream> using namespace std; char password[30][30]; void output(std::ostream &out); int main(){ ofstream out; password[0][0]=' '; for(int i=0,j=1;j<=26;j++) password[i][j]='a'+j-1; for(int i=1,j=0;i<=26;i++) password[i][j]=i+'0'; for(int i=1;i<=26;i++){ for(int j=1;i+j<=26;j++) password[i][j]='A'+i+j-1; } for(int i=26;i>=1;i--) for(int j=26;i+j>26&&j>=1;j--) password[i][j]='A'+i+j-27; out.open("cipher_key.txt", ios::binary); if(!out.is_open()) { cout << "fail to open cipher_key.txt\n"; return 1; } output(out); system("pause"); } void output(std::ostream &out){ for(int i=0;i<=26;i++){ for(int j=0;j<=26;j++){ if(j==0&&i!=0) cout<<left<<setw(2)<<password[i][j]-'0'<<" "; else cout<<left<<setw(2)<<password[i][j]<<" "; } cout<<endl; } for(int i=0;i<=26;i++){ for(int j=0;j<=26;j++){ if(j==0&&i!=0) out<<left<<setw(4)<<password[i][j]-'0'<<" "; else out<<left<<setw(4)<<password[i][j]<<" "; } out<<endl; } }
标签:size,int,Vector,实验,output,include,out From: https://www.cnblogs.com/qjj12-30/p/16942978.html