// txt2html.cpp: implementation of the txt2html class.
//
//////////////////////////////////////////////////////////////////////
#include "txt2html.h" #include <algorithm>
using namespace std;
/*初始化: 从word_font.map文件中读取与关健字对应的颜色值存入word_map中 *例: word_font.map中第二行为: * using blue * 则 word_map ["using"] = "blue"; * 这样在cpp文件中遇到using 关健字时,就可以用 using替换 */ void txt2html::init(){ ifstream map_file( "word_font.map" ); string word,font;
if( !map_file ) { cerr << "error : unable to open the initial file : word_font.map" << endl; exit(1); }
while( map_file >> word >> font ) { word_map.insert( make_pair( word,font ) ); cout << word << " : " << font << endl; }
cout << " Inital successfully..............." << endl; }
//读入待转换的cpp文件
void txt2html::read_file(std::string file){ ifstream is(file.c_str()); string textline;
//例:如果文件名为input.cpp ,则置filename = "input.html";
string::size_type it = file.find_last_of("."); if( it != string::npos ) filename.assign( file.begin(),file.begin() + it); else filename.assign( file.begin(),file.end() );
filename.append(".html");
if( !is ){ cerr << "error : unable to creat the input file : " << file << endl; exit(1); }
cout << "reading .................." << endl;
while( getline( is,textline ) ) { string::size_type st = textline.find("<"); while (st != textline.npos) { //将 "<" 替换为 html 中的 "<"
textline.replace( st,1,"<"); st = textline.find_first_of("<"); }
st = textline.find(">"); while( st != textline.npos) { //将 ">" 替换为 html 中的 ">"
textline.replace( st,1,">"); st = textline.find_first_of(">"); } /* * 想实现上面同样的替换功能,但失败了 replace( textline.begin(),textline.end() , "<", "<" ); replace( textline.begin(),textline.end() , ">", ">" ); */
lines_of_txt.push_back( textline ); //将文件中的每一行用vector容器存起来
cout << textline << endl; } }
//转换为html
void txt2html::tohtml(){ ofstream html( filename.c_str() );
if( !html ){ cerr << "error : unable to creat the output file : " << html << endl; exit(1); }
html << "" ; //html 中的文件开始行
vector<string>::size_type size = lines_of_txt.size();
cout << "size : " << size << endl;
for( vector<string>::size_type i = 0 ; i < size ; i ++) { //取出存储文件的容器中的每一行
istringstream line(lines_of_txt[i]); string word; int num = 1;
if( line >> word ) { int n = indent; /* 每一行开头进行缩进 如果遇到"}"不进行 n-- ,那么打印出的 "}" 缩进不好看,如下: { int c; } */ if( word == "{") indent ++; else if( word == "}") { indent --; n --; }
for( int i = 0 ; i < n ; i ++ ) for( int j = 0 ; j < indent_size ; j ++ ) html << " "; do { cout << word << endl; if( num > 1 ) { if( word == "{") indent ++; else if( word == "}") { indent --; n --; } }
num ++;
map<string,string>::iterator it = word_map.find(word); if( it != word_map.end() ) { html << "; html << "\""; html << it->second; html << "\">"; html << word;
if( word != "#include") { html << ""; } else{ while( line >> word ) html << word; html << ""; } } else html << word;
html << " "; }while( line >> word ); html << " "; } else html << " "; } html << " "; //html 中的文件结束行
}
|