簡單常識——關于stream 從文件中讀入一行
簡單,這樣就行了:
ifstream ifs("input.txt"); char buf[1000];
ifs.getline(buf, sizeof buf);
string input(buf);
當然,這樣沒有錯,但是包含不必要的繁瑣和拷貝,況且,如果一行超過1000個字符,就必須用一個循環和更麻煩的緩沖管理。下面這樣豈不是更簡單?
string input; input.reserve(1000); ifstream ifs("input.txt"); getline(ifs, input);
不僅簡單,而且安全,因為全局函數 getline 會幫你處理緩沖區用完之類的麻煩,如果你不希望空間分配發生的太頻繁,只需要多 reserve 一點空間。
這就是“簡單常識”的含義,很多東西已經在那里,只是我一直沒去用。
---------------------------------------------------------------------------
一次把整個文件讀入一個 string
我希望你的答案不要是這樣:
string input; while( !ifs.eof() ) { string line; getline(ifs, line); input.append(line).append(1, '\n'); }
當然了,沒有錯,它能工作,但是下面的辦法是不是更加符合 C++ 的精神呢?
string input( istreambuf_iterator<char>(instream.rdbuf()), istreambuf_iterator<char>() );
同樣,事先分配空間對于性能可能有潛在的好處:
string input; input.reserve(10000); input.assign( istreambuf_iterator<char>(ifs.rdbuf()), istreambuf_iterator<char>() );
很簡單,不是么?但是這些卻是我們經常忽略的事實。 補充一下,這樣干是有問題的:
string input; input.assign( istream_iterator<char>(ifs), istream_iterator<char>() );
因為它會忽略所有的分隔符,你會得到一個純“字符”的字符串。最后,如果你只是想把一個文件的內容讀到另一個流,那沒有比這更快的了:
fstream fs("temp.txt"); cout << fs.rdbuf();
因此,如果你要手工 copy 文件,這是最好的(如果不用操作系統的 API):
ifstream ifs("in.txt"); ofstream ofs("out.txt"); ofs << in.rdbuf();
-------------------------------------------------------------------------
open 一個文件的那些選項
ios::in Open file for reading ios::out Open file for writing ios::ate Initial position: end of file ios::app Every output is appended at the end of file ios::trunc If the file already existed it is erased ios::binary Binary mode
-------------------------------------------------------------------------
還有 ios 的那些 flag
flag |
effect if set |
ios_base::boolalpha |
input/output bool objects as alphabetic names (true, false). |
ios_base::dec |
input/output integer in decimal base format. |
ios_base::fixed |
output floating point values in fixed-point notation. |
ios_base::hex |
input/output integer in hexadecimal base format. |
ios_base::internal |
the output is filled at an internal point enlarging the output up to the field width. |
ios_base::left |
the output is filled at the end enlarging the output up to the field width. |
ios_base::oct |
input/output integer in octal base format. |
ios_base::right |
the output is filled at the beginning enlarging the output up to the field width. |
ios_base::scientific |
output floating-point values in scientific notation. |
ios_base::showbase |
output integer values preceded by the numeric base. |
ios_base::showpoint |
output floating-point values including always the decimal point. |
ios_base::showpos |
output non-negative numeric preceded by a plus sign (+). |
ios_base::skipws |
skip leading whitespaces on certain input operations. |
ios_base::unitbuf |
flush output after each inserting operation. |
ios_base::uppercase |
output uppercase letters replacing certain lowercase letters. |
There are also defined three other constants that can be used as masks:
constant |
value |
ios_base::adjustfield |
left | right | internal |
ios_base::basefield |
dec | oct | hex |
ios_base::floatfield |
scientific | fixed |
--------------------------------------------------------------------------
用我想要的分隔符來解析一個字符串,以及從流中讀取數據
這曾經是一個需要不少麻煩的話題,由于其常用而顯得尤其麻煩,但是其實 getline 可以做得不錯:
getline(cin, s, ';'); while ( s != "quit" ) { cout << s << endl; getline(cin, s, ';'); }
簡單吧?不過注意,由于這個時候 getline 只把 ; 作為分隔符,所以你需要用 ;quit; 來結束輸入,否則 getline 會把前后的空格和回車都讀入 s ,當然,這個問題可以在代碼里面解決。
同樣,對于簡單的字符串解析,我們是不大需要動用什么 Tokenizer 之類的東西了:
#include <iostream> #include <sstream> #include <string>
using namespace std;
int main() { string s("hello,world, this is a sentence; and a word, end."); stringstream ss(s); for ( ; ; ) { string token; getline(ss, token, ','); if ( ss.fail() ) break; cout << token << endl; } }
輸出:
hello world this is a sentence; and a word end.
很漂亮不是么?不過這么干的缺陷在于,只有一個字符可以作為分隔符。
--------------------------------------------------------------------------
把原本輸出到屏幕的東西輸出到文件,不用到處去把 cout 改成 fs
#include <iostream> #include <fstream>
using namespace std;
int main() { ofstream outf("out.txt"); streambuf *strm_buf=cout.rdbuf(); cout.rdbuf(outf.rdbuf()); cout<<"write something to file"<<endl; cout.rdbuf(strm_buf); //recover cout<<"display something on screen"<<endl; system("PAUSE"); return 0; }
輸出到屏幕的是:
display something on screen
輸出到文件的是:
write something to file
也就是說,只要改變 ostream 的 rdbuf ,就可以重定向了,但是這招對 fstream 和 stringstream 都沒用。
--------------------------------------------------------------------------
關于 istream_iterator 和 ostream_iterator
經典的 ostream_iterator 例子,就是用 copy 來輸出:
#include <iostream> #include <fstream> #include <sstream> #include <algorithm> #include <vector> #include <iterator>
using namespace std;
int main() { vector<int> vect; for ( int i = 1; i <= 9; ++i ) vect.push_back(i); copy(vect.begin(), vect.end(), ostream_iterator<int>(cout, " ") ); cout << endl; ostream_iterator<double> os_iter(cout, " ~ "); *os_iter = 1.0; os_iter++; *os_iter = 2.0; *os_iter = 3.0; }
輸出:
1 2 3 4 5 6 7 8 9 1 ~ 2 ~ 3 ~
很明顯,ostream_iterator 的作用就是允許對 stream 做 iterator 的操作,從而讓算法可以施加于 stream 之上,這也是 STL 的精華。與前面的“讀取文件”相結合,我們得到了顯示一個文件最方便的辦法:
copy(istreambuf_iterator<char>(ifs.rdbuf()), istreambuf_iterator<char>(), ostreambuf_iterator<char>(cout) );
同樣,如果你用下面的語句,得到的會是沒有分隔符的輸出:
copy(istream_iterator<char>(ifs), istream_iterator<char>(), ostream_iterator<char>(cout) );
那多半不是你要的結果。如果你硬是想用 istream_iterator 而不是 istreambuf_iterator 呢?還是有辦法:
copy(istream_iterator<char>(ifs >> noskipws), istream_iterator<char>(), ostream_iterator<char>(cout) );
但是這樣不是推薦方法,它的效率比第一種低不少。 如果一個文件 temp.txt 的內容是下面這樣,那么我的這個從文件中把數據讀入 vector 的方法應該會讓你印象深刻。
12345 234 567 89 10
程序:
#include <iostream> #include <fstream> #include <algorithm> #include <vector> #include <iterator>
using namespace std;
int main() { ifstream ifs("temp.txt"); vector<int> vect; vect.assign(istream_iterator<int>(ifs), istream_iterator<int>() );
copy(vect.begin(), vect.end(), ostream_iterator<int>(cout, " ")); }
輸出:
12345 234 567 89 10
很酷不是么?判斷文件結束、移動文件指針之類的苦工都有 istream_iterator 代勞了。
-----------------------------------------------------------------------
其它算法配合 iterator
計算文件行數:
int line_count = count(istreambuf_iterator<char>(ifs.rdbuf()), istreambuf_iterator<char>(), '\n');
當然確切地說,這是在計算文件中回車符的數量,同理,你也可以計算文件中任何字符的數量,或者某個 token 的數量:
int token_count = count(istream_iterator<string>(ifs), istream_iterator<string>(), "#include");
注意上面計算的是 “#include” 作為一個 token 的數量,如果它和其他的字符連起來,是不算數的。
------------------------------------------------------------------------ Manipulator
Manipulator 是什么?簡單的說,就是一個接受一個 stream 作為參數,并且返回一個 stream 的函數,比如上面的 unskipws ,它的定義是這樣的:
inline ios_base& noskipws(ios_base& __base) { __base.unsetf(ios_base::skipws); return __base; }
這里它用了更通用的 ios_base 。知道了這一點,你大概不會對自己寫一個 manipulator 有什么恐懼感了,下面這個無聊的 manipulator 會忽略 stream 遇到第一個分號之前所有的輸入(包括那個分號):
template <class charT, class traits> inline std::basic_istream<charT, traits>& ignoreToSemicolon (std::basic_istream<charT, traits>& s) { s.ignore(std::numeric_limits<int>::max(), s.widen(';')); return s; }
不過注意,它不會忽略以后的分號,因為 ignore 只執行了一次。更通用一點,manipulator 也可以接受參數的,下面這個就是 ignoreToSemicolon 的通用版本,它接受一個參數, stream 會忽略遇到第一個該參數之前的所有輸入,寫起來稍微麻煩一點:
struct IgnoreTo { char ignoreTo; IgnoreTo(char c) : ignoreTo(c) {} }; std::istream& operator >> (std::istream& s, const IgnoreTo& manip) { s.ignore(std::numeric_limits<int>::max(), s.widen(manip.ignoreTo)); return s; }
但是用法差不多:
copy(istream_iterator<char>(ifs >> noskipws >> IgnoreTo(';')), istream_iterator<char>(), ostream_iterator<char>(cout) );
其效果跟 IgnoreToSemicolon 一樣。
|