Binary -------------------------
ifs.read(as_bytes(i),sizeof(int));
ofs.write(as_bytes(v[i]),sizeof(int));
template<class T>
char* as_bytes(T& i){
void* addr=&i;
return static_cast<char*>(addr);
}
---------------------------------
fstream fs(name.c_str());
if (!fs) error("can't open",name);
fs.seekg(5); //Move reading position
char ch;
fs>>ch;
cout<<"character[5] is"<<ch<<'('<<int(ch)<<")/n";
fs.seekp(1); //Move writing position
fs<<'y';
---------------------------------
ofstream ofs(name,ios_base::app); //末尾追加
fstream fs("myfile",ios_base::in|ios_base::out); //Both In & Out
if (!fs) ifstream ifs("no-file-of-this-name"); //打开一个不存在文件,会自建。
ios_base::binary <-> 2进制方式存取内存
cout<<general<<setprecision(8)<<1234.5678<<endl;
cout<<123456<<'|'<<setw(4)<<123456<<'|'<<setw(8)<<123456<<'|'<<endl;
cout<<showbase<<1234<<oct<<1234<<hex<<1234<<endl; //OPT
cin.unsetf(ios::dec);
cin.unsetf(ios::oct);
cin.unsetf(ios::hex);
cin>>a>>b>>c>>d;
1234 0x4d2 02322 02322
->
1234 1234 1234 1234
cout<<1234.5678<<fixed<<1234.5678<<scientific<<1234.5678;
void fill_vector(istream& ist,vector<int>& v,char terminator){
int i=0;
while(ist>>i) v.push_back(i);
if(ist.eof()) return;
if(ist.bad()) error("ist is bad");
if(ist.fail()) {
ist.clear(); //清除Fail状态,--为了是否terminator了?
char c;
ist>>c;
if (c!=terminator){
ist.unget(); //put charactor back
ist.clear(ios_base::failbit); //set state to fail()
}
}
}
int get_int(int low,int high,const string& greeting,const string& sorry){
cout<<greeting<<":["<<low<<':'<<high<<"/n";
while(true){
int n=get_int();
if(low<=n&&n<=high) return n;
cout<<soory<<":["<<low<<':'<<high<<"/n";
}
}
int get_int(int low,int high){
int n=0;
while(true){
if(cin>>n) return n;
cout<<"Sorry,that was nott a number"<<endl;
skip_to_int();
}
}
void skip_to_int(){
if(cin.fail()){
cin.clear();
char ch;
while(cin>>ch){
if(isdigit(ch)){
cin.unget();
return;
}
}
}
error("no input!");
}
ostream& operator<<(ostream& os,const Data& d){
return os<<'('<<d.year()<<','<<d.month()<<','<<d.day()<<')';
}
istream& operator>>(istream& is,Date& dd){
int y,m,d;
char ch1,ch2,ch3,ch4;
is>>ch1>>y>>ch2>>m>>ch3>>d>>ch4;
if (!is) return is;
if (ch1!='('||ch2!=','||ch3!=','||ch4!=')'){
is.clear(ios_base::failbit);
return is;
}
dd=Date(y,Date::Month(m),d);
return is;
}