这是代码:
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
#include <vector>
#include <set>
#include <cctype>
using namespace std;
vector< string > types;
set< string > names;
int main() {
types.push_back( "int" );
types.push_back( "char" );
types.push_back( "float" );
types.push_back( "double" );
types.push_back( "bool" );
types.push_back( "unsigned" );
types.push_back( "long" );
types.push_back( "short" );
types.push_back( "wchar_t" );
// ect
fstream in( "input.cpp", fstream::in );
string row;
string tmp;
while( in >> tmp ) {
if( tmp == "struct" || tmp == "class" ) {
in >> tmp;
string::iterator it = find( tmp.begin(), tmp.end(), '{' );
tmp.erase( it, tmp.end() );
types.push_back( tmp );
}
row += tmp;
}
for( int i=0; i<types.size(); ++i ) {
int it=-1;
while( ( it=row.find( types[ i ], it+1 ) ) ) {
if( it == -1 ) break;
int spos;
for( spos=it; row[ spos ] != '*'; ++spos );
spos++;
string ptr;
while( ( isalnum( ( int )row[ spos ] ) || row[ spos ] == '_' ) && spos < row.size() ) {
ptr += row[ spos ];
spos++;
}
names.insert( ptr );
}
}
for( set< string >::iterator i=names.begin(); i!=names.end(); ++i ) {
cout << *i << " ";
}
return 0;
}
我基本上做的是,我将整个输入程序放在一行中,没有空格,然后检查用户定义的结构或类,我将它们插入到类型向量中,最后我搜索每种类型,如果存在的话在行中形成<type>*
。然后,我打印它。