[C++][基礎]5_标準庫類型
5.1 标準庫string類型
5.1.1 有用操作
(1) getline
Eg:
string line
while(getline(cin, line))
cout << line << endl;
(2) s.empty()
如果s是空串,傳回true,否則傳回false。
(3) s.size()
傳回s中字元個數。
(4) string::size_type類型
5.2 标準庫bitset類型
5.3 标準IO庫
5.3.1 IO标準庫類型
頭檔案 類型
iostream istream
ostream
iostream
fstream ifstream
ofstream
fstream
sstream istringstream
ostringstream
stringstream
IO對象不可複制或指派。
Eg:
ofstream out1, out2;
out1 = out2; //error
ofstream print(ofstream);
out2 = print(out2); //error
5.3.2 條件狀态
strm::iostate
strm::badbit
strm::failbit
strm::eofbit
s.eof()
s.fail()
s.bad()
s.good()
s.clear()
s.clear(flag)
s.setstate(flag)
s.rdstate()
5.3.3 檔案的輸入輸出
1.檢查檔案是否打開
Eg:
ifstream
input;
if(!input)
{
cerr << "error: unable to open
the file: " << input << endl;
}
2.将檔案流重新綁定
如果要把發fstream流和另一個不同檔案關聯,則必須先關閉現在的檔案,然後打開另一個檔案。
3.清除檔案流的狀态
如果要重用檔案流讀寫多個檔案,必須在讀另一個檔案之前調用clear清除該流的狀态。
5.3.4 檔案模式
in
out
app 在每次寫之前找到檔案尾
ate 打開檔案後立即定位在檔案尾
trunc 打開檔案時清空已存在的檔案流
binary
5.3.5 fstream的用法
1.打開檔案open
2.關閉檔案close
3.讀寫檔案
(1)文本檔案讀寫<<, >>
(2)二進制檔案讀寫
put()
get(),
getline()
讀寫資料塊:read(),
write()
4.檢測檔案尾
if(file.eof())
5.檔案定位
File.seekg(1024, ios::cur) //檔案指針從檔案目前位置後移1024個位元組
File.seekg(1024, ios::beg) //檔案指針從檔案開頭後移1024個位元組