2013-10-14 34 views
0

我正在使用strstr以顯示C++中類的名稱。我的代碼的問題是它尋找這個字符串:使用C++ strstr查找c字符串,然後計數

"class " 

整個輸入文件。所以,結果是這樣的:

The CLASS name is class locCounter 
The CLASS name is class "; 

第二行不應該在那裏,它基本上從下面的代碼,顯示7行,它不應該。

int locCounter::classCounter() 
{ 
    int count = 0; 
    ifstream theOtherFile ("loc2.cpp"); 
    while (! theOtherFile.eof()) 
    { 
     const char *one = "class "; 
     getline(theOtherFile, otherFileData); 
     const char *result = otherFileData.c_str(); 
     while ((result = strstr(result, one)) != NULL) 
     { 
      cout << "The CLASS name is " << result << endl; 
      result++; 
     } 
    } 
} 

除此之外,我不知道我怎麼能得到的功能也開始從中查找單詞「類」,直到它擊中班上最後花括號時間計數的行數。

謝謝。

+1

使用正確的C++解析器,因爲你的方法不起作用,請參閱http://stackoverflow.com/questions/2318347/library-to-parse-c-c-source-code –

+1

基本上,你想要一個完整的C++解析器。對C++來說,除了class C {...};還有更多。除了字符串文字之外,還有一些東西,比如'template void f();'或'class {int x;} v;'。 –

+0

@IgorTandetnik - 我知道,但現在,我真的需要它來查找類名和一些函數名。 – UndefinedReference

回答

0

變化

while ((result = strstr(result, one)) != NULL) 

if ((result = strstr(result, one)) != NULL) 

while循環會在你的文件的"class "所有出現,並且如果語句查找只是第一次出現。

+0

這實際上在這種情況下不起作用。 – UndefinedReference

+0

然後,一旦遇到第一個事件,您就可以跳出循環。 –

0

也許你應該嘗試一個正則表達式引擎,如Boost Regex

然後你可以使用正則表達式像this question來養活他們的引擎。

試試看。這很簡單。

相關問題