c++ io 流操作 以及字串操作
阿新 • • 發佈:2018-12-14
字元流操作如下:
#include <fstream> void main(){ char* fname = "D://dest.txt"; //開啟輸出流 ofstream fout(fname); //建立失敗 if (fout.bad()){ cout << "開啟失敗" << endl; return; } //向文字中寫入內容 fout << "jack" << endl; fout << "rose" << endl; fout.close(); //讀取 ifstream fin(fname); if (fin.bad()){ cout << "讀取失敗" << endl; return; } char ch; while (fin.get(ch)){ cout << ch; } fin.close(); system("pause"); }
位元組流操作:
void main(){ char* src = "D://lgj.jpg"; char* dest = "D://copylgj.jpg"; //輸入流,最後一個引數是 ifstream fin(src,ios::binary); ofstream fout(dest,ios::binary); if (fin.bad() || fout.bad()){ return; } while (!fin.eof()){ char buffer[1024] = {0}; //讀取 fin.read(buffer,1024); //寫入 fout.write(buffer,1024); } fin.close(); fout.close(); system("pause"); }
把物件序列化到硬碟上操作:
void main() { Person p1("柳巖", 22); Person p2("rose", 18); //輸出流 ofstream fout("c://c_obj.data", ios::binary); fout.write((char*)(&p1), sizeof(Person)); //指標能夠讀取到正確的資料,讀取記憶體區的長度 fout.write((char*)(&p2), sizeof(Person)); fout.close(); //輸入流 ifstream fin("c://c_obj.data", ios::binary); Person tmp; fin.read((char*)(&tmp), sizeof(Person)); tmp.print(); fin.read((char*)(&tmp), sizeof(Person)); tmp.print(); system("pause"); }
字串操作
void main()
{
string s1 = "lgj ";
string s2(" lt ");
string s3 = s1 + s2;
cout << s3 << endl;
//轉c字串
const char* c_str = s3.c_str();
cout << c_str << endl;
//s1.at(2);
system("pause");
}
容器
//容器
#include <vector>
void main()
{
//動態陣列
//不需要使用動態記憶體分配,就可以使用動態陣列
vector<int> v;
v.push_back(12);
v.push_back(10);
v.push_back(5);
for (int i = 0; i < v.size(); i++)
{
cout << v[i] << endl;
}
system("pause");
}