[情報] 輸出/輸入格式處理器的設計
以下是由中大織夢板轉來的
********************************************************************
C++ 的輸出/輸入與其他語言不太一樣,它是透過 << 與 >> 兩個運算子來
協助輸出與輸入的動作,如果用慣了 C 的 print ,可能會不太習慣,
但若使用者自行設計一些格式處理器,則 C++ 的輸出/輸入就變得非常靈活。
以下是利用自行設計的 Split 輸出格式處理器,使得之後物件的輸出能自動
以指定的格數分開列印,同時此輸出格式處理器也可自行指定分隔的字元。
***使用方式***
string a = "hello" ;
int    b = 1992 ;
char  *c = "math" ;
double d = 3.14159 ;
cout << split(2,'*') << a << endl ;
cout << split(3,'=') << b << endl ;
cout << split(3,'-') << c << endl ;
cout << split(2) << d << endl ;
***輸出***
h**e**l**l**o
1===9===9===2
m---a---t---h
3  .  1  4  1  5  9
以上的 split 為輸出格式處理器。
程式碼為:
#include <iostream>
#include <sstream>
#include <string>
using namespace std ;
class  Split {
  private :
    int       n ;
    char      sep ;
    ostream  *ptr ;
  public :
    Split  operator() ( int s , char separator = ' ' ) {
        n = s ;
        sep = separator ;
        return  *this ;
    }
    friend  Split  operator<< ( ostream& out , Split foo ) {
        foo.ptr = &out ;
        return  foo ;
    }
    template <class T>
    friend  ostream&  operator<< ( Split split , const T& foo ) {
        ostringstream  ostr ;
        ostr << foo ;
        string  str = ostr.str() ;
        for ( int i = 0 ; i < str.size()-1 ; ++i )
            *(split.ptr) << str[i] << string(split.n,split.sep) ;
        *(split.ptr) << str[str.size()-1] ;
        return  *(split.ptr) ;
    }
};
Split  split ;
int main() {
    string a = "hello" ;
    int    b = 1992 ;
    char  *c = "math" ;
    double d = 3.14159 ;
    cout << split(2,'*') << a << endl ;
    cout << split(3,'=') << b << endl ;
    cout << split(3,'-') << c << endl ;
    cout << split(2) << d << endl ;
    return 0 ;
}
有關格式處理器的設計方法可參考『深度學習C++』網頁內資料下載區的
補充教材。
***************************************************************
--
※ 發信站: 批踢踢實業坊(ptt.cc) 
◆ From: 220.134.25.64
C_and_CPP 近期熱門文章
PTT數位生活區 即時熱門文章
                            12
                        
                            32