因为总觉得上回写的C++代码太过蹩脚了,心有不甘。毕竟C++是一个很优秀的语言,并且有着众多出色的模板库,这么简单的一个小程序被我给用成那样,真的是太惭愧了。代码绝对不应该这么臃肿。实际上我有几个概念模糊不清了,所以导致了代码的臃肿,一个是输入输出流的概念模糊了,还有一个是正则表达式应用不熟悉。于是重温了输入输出流,并且详细的阅读了正则表达式的Boost库的说明文档。新写的代码如下,明显比原来的代码优雅了许多:
#include <string> #include <boost/regex.hpp> #include <iostream> #include <fstream> #include <sstream>using namespace std; using namespace boost; string filter( const string in ) { regex expr("\"(\\w+):(\\w+)%(\\w+)\""); string fmt("$1:$2*$3,\n"); ostringstream ostring; ostream_iterator<char> oi(ostring); regex_replace( oi, in.begin(), in.end(), expr, fmt, (match_default | format_no_copy) ); return ostring.str(); } int main(int argc, const char* argv[]) { if( argc < 3 ) { cout<< "Please enter 2 filenames(e.g. In.txt Out.txt)" << endl; return 1; } ifstream in( argv[1] ); ofstream out( argv[2] ); ostringstream buf; buf << in.rdbuf(); out << filter( buf.str() ) << flush; }
Copyright @ 2007-2012 敏韬网(敏而好学,文韬武略--MinTao.Net)(学习笔记) Inc All Rights Reserved. 闵涛 E_mail:admin@mintao.net(欢迎提供学习资源)
鄂公网安备 42011102001154号
站长:MinTao ICP备案号:鄂ICP备11006601号-18