作者oxoxoxox (圈叉)
看板C_and_CPP
标题[情报] 输出/输入格式处理器的设计
时间Sat Oct 13 08:05:13 2007
以下是由中大织梦板转来的
********************************************************************
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