#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的参数改为char:
原因:当int类型写入是,每个数据占四个字节,以char类型输出时每个数据占一个字节,产生空格。
#pragma once #include<iostream> using namespace std; template<typename T> class Vector { public: Vector(int n) :size(n) { p = new T[size]; } Vector(int n, T value) :size(n) { p = new T[size]; for (int i = 0; i < size; i++) p[i] = value; } Vector(const Vector<T>& x):size(x.size) { p = new T[size]; for(int i=0;i<size;i++) p[i]=x.p[i]; } ~Vector() { delete[]p; } int get_size() { return size; } T& at(int i) { return p[i]; } T& operator[](int i) { return p[i]; } friend void output(const Vector<T>& x) { for (int i = 0; i < x.size; i++) cout << x.p[i] << ","; cout << endl; } private: T* p; int size; };
#include <iostream> #include "Vector.h" 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<string> #include<fstream> using namespace std; void output(std::ostream& out) { int row = 1; char a[26][26]; cout << " "; out << " "; for (char i = 'a'; i <= 'z'; i++) { cout << i << " "; out << i << " "; } cout << endl; out << endl; for (int i = 0; i < 26; i++) { cout << i + 1 << " "; out << i + 1 << " "; for (int j = 0; j < 26; j++) { a[i][j] = 'A' + char((i + j + 1) % 26); cout << a[i][j] << " "; out << a[i][j] << " "; } cout << endl; out << endl; } } int main() { ofstream out; out.open("cipher_key.txt", ios::out); if (!out.is_open()) { cout << "fail to open cipher_ke.text" << endl; return 1; } output(out); out.close(); }
标签:std,int,Vector,实验,output,include,size From: https://www.cnblogs.com/czba/p/16950260.html