C++的tie()函数
鏈接:http://tech.quarkjoker.com/2011/06/22/C++%E7%9A%84tie()%E5%87%BD%E6%95%B0
今天看C ++ primer 時,看到了iOS::tie() 函數(shù)。不明白其含義,跟不知道作用。于是上網(wǎng)查了一下。
cplusplus.com 給出的定義是:
ostream* tie ( ostream* tiestr ); //將tiestr指向的輸出流綁定的該對象上,并返回上一個綁定的輸出流指針。
什么意思呢?
就是說對于一個ios(輸入輸出流)對象,可以把一個輸出流和它“綁定”起來。不帶參數(shù)執(zhí)行,返回“綁定”的輸出流指針;帶一個輸出流指針作為參數(shù),則重新設(shè)置綁定的對象,并返回前任綁定對象(指針)。
但是,什么是“綁定”呢?
比方說,對于下面這個程序:
#include <iostream> #include <fstream> using namespace std;int main () {ofstream ofs;ofs.open ("test.txt");cin.tie (&ofs); //注釋掉這一行試試看*cin.tie() << "There will be some text:";char c;while(cin >> c){ofs << c;}ofs.close();return 0; }
用linux下watch命令(windows下還不知道有沒有什么類似的東西,如果沒有就用本辦法:手動關(guān)掉再打開)實時察看test.txt文件,會發(fā)現(xiàn)每當你在終端里敲幾個字后按下回車,test.txt文件里的文字就多了幾個。
而如果你將代碼中標注的那一行注釋掉,就會發(fā)現(xiàn),test.txt只有在程序運行結(jié)束(linux下按ctrl+d,windows下是ctrl+z結(jié)束輸入)后才會有東西出現(xiàn)。
這就是“綁定”的效果,每當被“綁定”的對象有出入或輸出操作,就會自動刷新“綁定”的對象的緩沖區(qū),以達到實時的效果。
?
Remarks
tie causes two streams to be synchronized, such that, operations on one stream occur after operations on the other stream are complete.
Example
In this example, by tying cin to cout, it is guaranteed that the "Enter a number:" string will go to the console before the number itself is extracted from cin. This eliminates the possibility that the "Enter a number:" string is still sitting in the buffer when the number is read, so that we are certain that the user actually has some prompt to respond to. By default, cin and cout are tied.
Copy #include <ios> #include <iostream>int main( ) {using namespace std;int i;cin.tie( &cout );cout << "Enter a number:";cin >> i; }?
總結(jié)
以上是生活随笔為你收集整理的C++的tie()函数的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: cin.tie(0)和ios::sync
- 下一篇: exp table oracle,ora