一道有趣的题
会有兴趣写点有用的东西,现在我有这么一个需求,根据一个c++的头文件生成一个文本文件(其实是lua文件,作为语法测试用的桩代码)
c++头文件就是类似这样
#ifndef __XXX_H__
#define __XXX_H__
//sdfasdfas
void func0();
void func1(float x);
enum E_XXX
{
E_XXX_A,
E_XXX_B,
E_XXX_C,
};
bool func2(int x, int y = 0);
/*sdfsdfsf*/
int func3(int x, float y, double z);
#endif //__XXX_H__
我只关心函数声明的部分。生成的文本文件类似这样
function func0()
end
function func1()
end
function func2()
return (math.random(2)==1)
end
function func3()
end
每一个函数声明对应一个同 本来的返回类型是bool,那么function有函数体return (math.random(2)==1),其余的返回类型都留空即可,函数参数也无视 名的function
这个问题,初看是个编译原理的题,感觉很难,其实只是个文件操作
最好的思路,把所有返回类型存储到字典中,然后直接对.h文件进行返回类型匹配,然后用正则表达式对
当然还要考虑c++的函数重载问题。不过这种问题,如果遇到自定义返回类型,我们怎么办,你不可能把所有的返回类型都放入字典中。
所以有了下面的思路,注:C++ 11貌似有正则表达式的库,由于pipi使用的是vs2008,所以只能自己实现字符串匹配。
1 // c++header.cpp : 定义控制台应用程序的入口点。 2 // 3 4 #include "stdafx.h" 5 #include <iostream> 6 #include <fstream> 7 #include <string> 8 #include <vector> 9 #include <algorithm> 10 #include <set> 11 using namespace std; 12 13 /** 14 * 本来打算用字典,但是考虑到有自定义类型,不知可不可以搞 15 * 16 **/ 17 18 int _tmain(int argc, _TCHAR* argv[]) 19 { 20 21 ifstream fp; 22 ofstream luagtext; 23 char read_text[256] = {0}; 24 25 string FunName,ReturnType; 26 string result = "function "; 27 28 set <string> FunameSet; 29 set <string> :: const_iterator FunameSet_RcIter; 30 31 fp.open("d://test.h"); 32 33 luagtext.open("d://lua.txt"); 34 35 if (!fp) 36 { 37 cout<<"cant open the header file!\n"<<endl; 38 fp.close(); 39 } 40 if(!luagtext) 41 { 42 43 cout<<"cant open the luagtext file!\n"<<endl; 44 fp.close(); 45 } 46 47 while(fp.getline(read_text,sizeof(read_text),'\n')) 48 { 49 string textstr; 50 textstr = read_text; 51 basic_string <char>::size_type indexCha,indexCha2; 52 53 indexCha = textstr.find('('); / /对(前的函数名进行搜索 54 indexCha2 = textstr.find(';'); //检测结尾的;号 去除掉一些#define te (a+b) 55 56 if(indexCha!=string::npos&&indexCha2!=string::npos) 57 58 while(textstr[indexCha-1]!=32) 59 { 60 FunName +=textstr[--indexCha]; //函数名前类型进行判断 去掉一些const int a= (2+3); 61 } 62 int index = 0; 63 64 while(textstr[index]!=32) 65 { 66 ReturnType += textstr[index++]; 67 } 68 69 vector<char> funname; 70 for(int i=0;i<FunName.length();i++) 71 { 72 funname.push_back(FunName[i]); 73 } 74 75 reverse(funname.begin(),funname.end()); 76 77 for (int i=0;i<FunName.length();i++) 78 { 79 FunName[i] = funname.at(i); 80 } 81 82 83 result+=FunName; //实现反转 84 85 result+="()\n"; 86 87 if("bool"==ReturnType) //类型为bool 88 { 89 result +="return (math.random(2)==1)\n"; 90 } 91 result +="end\n"; 92 FunameSet_RcIter =FunameSet.find(FunName); 93 94 if(FunameSet_RcIter==FunameSet.end()) //判断是否包含这一个函数名 防止重载 95 { 96 luagtext.write(result.c_str(),result.length()); 97 } 98 99 FunameSet.insert(FunName); 100 } 101 102 result = "function "; 103 FunName.clear(); 104 ReturnType.clear(); 105 } 106 fp.close(); 107 luagtext.close(); 108 system(" d:/lua.txt"); 109 110 111 return 0; 112 }
我自豪 我是一名软件工程师。