1. 程式人生 > >C++中的IO類 iostream fstream stringstream 小結

C++中的IO類 iostream fstream stringstream 小結

               

        以前學習C++的時候, 總是囫圇吞棗地理解cin, cout等東東, 最近又在複習C++,  複習到IO類這一章節的時候, 有點感觸, 所以呢, 打算記錄一下。

         俗話說, 一圖勝過千言萬語, 這不是沒有道理的, 下面, 我們來看看基本IO類的繼承結構:


      在我們寫C++簡單程式碼的時候, 最喜歡寫#include <iostream>  , 那麼, 這實際上是在包括IO流的標頭檔案, 而用using namespace std;則表示用標準空間, 這樣才能用cin,cout, endl等東東啊。

      從上圖看, 實際上可以把IO類分為三類:

      1. iostream類: 負責與控制檯輸入輸出打交道, 這個我們已經很熟悉了。   注意: 實際具體又可以區分為:istream和ostream

      2. fstream類:   負責與檔案輸入輸出打交道, 這個我們接觸過。  注意: 實際具體又可以區分為:ifstream和ofstream

      3. stringstream類:負責與string上的輸入輸出打交道, 這個我們暫時還真沒用過。  注意: 實際具體又可以區分為:istringstream和ostringstream

       下面, 我們來一一學習/複習:

      1. IO類之iostream

          iostream類的物件, 如cin, cout, 會直接與控制檯輸入輸出關聯, 下面我們來看看最簡單的程式:

#include <iostream>using namespace std;int main()int i = -1;  cin >> i; // cin從控制檯接收輸入, 並儲存在i中 cout << i << endl; // count把i的值輸出到控制檯 return 0;}

     很簡單很好理解吧。

     2. IO類值之fstream

      fstream的物件, 與檔案建立關聯, 我們已經很熟悉了, 直接看程式碼吧:

#include <iostream>#include <string>#include <fstream>
using namespace std;int main()ifstream in("test.txt"); // 建立in與檔案test.txt之間的額關聯 if(!in) {  cout << "error" << endl;  return 1; } string line; while(getline(in, line)) {  cout << line << endl;  } return 0;}

    3. IO類之stringstream

     stringstream的物件與記憶體中的string物件建立關聯, 往string物件寫東西, 或者從string物件讀取東西。

     我們先看這樣一個問題, 假設test.txt的內容為:

lucy 123 

lili 234 456

tom 222 456 535

jim 2345 675 34 654

     其中每行第一個單詞是姓名, 後面的數字都是他們的銀行卡密碼, 當然啦, jim的銀行卡最多, 有4張, 現在, 要實現如下輸出, 該怎麼做呢?

lucy 123x 

lili 234x   456x 

tom 222x   456x   535x 

jim 2345x   675x   34x   654x 

     直接看程式吧:

#include <iostream>#include <string>#include <fstream>#include <sstream>using namespace std;int main()ifstream in("test.txt"); // 建立in與檔案test.txt之間的額關聯 if(!in) {  cout << "error" << endl;  return 1; } string line;  string password; while(getline(in, line)) {  istringstream ss(line); // 建立ss與line之間的關聯  int i = 0;  while(ss >> password) // ss從line讀取東西並儲存在password中  {    cout << password + (1 == ++i ? "" : "x") << " ";  }    cout << endl; } return 0;}

       結果ok.

       下面, 我們來看看如何利用istringstream實現字串向數值的轉化:

#include <iostream>#include <string>#include <sstream>using namespace std;int main()int a = -1string s = "101"istringstream is(s); // 建立關聯 cout << is.str() << endl; // 101,  看來is和s確實關聯起來了啊 is >> a; cout << a << endl; // 101 return 0;}


      當然, 我們也可以把數字格式化為字串, 如下(下面這個程式有問題):

#include <iostream>#include <string>#include <sstream>using namespace std;int main()string str; ostringstream os(str); // 建立關聯, 但實際沒有關聯上啊!!! os << "hello"cout << str << endl// str居然是空, 怎麼不是"abc"呢? 我不理解 return 0;}
     看來, 上面的關聯是不成功的, 改為:
#include <iostream>#include <string>#include <sstream>using namespace std;int main()int a = -1ostringstream os; os << "hello" << a; cout << os.str() << endl; // hello-1 return 0;}

      所以, 我總結呢, istringstream的關聯是ok的, 但是ostringstream不能依賴於關聯, 不知道C++為啥要這樣搞。

      好吧, 到此為止, 總算是對三種類型的IO類有所掌握了。