2011-06-06 108 views
1

我試圖使用string :: find方法來確定字符串「hello」(帶有空格之前和之後)是否存在於.txt文件的一行中。如果是這樣,它應該打印出行號(位置不重要)。問題是,它沒有找到字符串。請幫忙。string :: find找不到匹配

int main() { 
    string key (" hello "); 
    ifstream myReadFile; 
    myReadFile.open("test.txt"); 
    string s; 
    int lineCount = 1; 
    int found; 
    if (myReadFile.is_open()) { 
     while (!myReadFile.eof()) { 
      getline(myReadFile, s); 
      found = s.find(key); 
      if(found != string::npos) { 
       cout<<lineCount<<endl; 
       lineCount++; 
      } 
     } 
    } 
    myReadFile.close(); 
    return 0; 
} 
+0

運行它在調試器中,看看它出錯的地方。 – 2011-06-06 02:59:54

+0

注意:'string :: find()'不會**返回一個'int'。請使用std :: string :: size_type。 – 2011-06-06 03:20:27

+0

Martin:雖然我更喜歡這種結構,但OP的程序實際上並沒有錯誤地處理最後一行;如果你嘗試在最後一行之後讀取一行,getline將清除字符串。所以總是有一個額外的循環,'s'是空的,但這不會使輸出錯誤。 – 2011-06-06 03:21:00

回答

0

似乎怎麼做,你有它只是計算的是在他們這個字符串的行數。您應該在循環的每次迭代中增加行號var,而不僅僅是在找到字符串時。

int main() { 
    std::string key (" hello "); 
    ifstream myReadFile; 
    myReadFile.open("test.txt"); 


    if (myReadFile) { 

     std::string line; 
     int line_number = 0; 
     while (std::getline(myReadFile, line)) { 
      line_number++;     
      if (line.find(key) != std::string::npos) 
       std::cout << line_number << std::endl; 
     } 

    } else { 
     std::cout << "Error opening file\n"; 
    } 
} 
+0

看不到'if(myReadFile)'的用法' – 2011-06-06 03:21:26

0

int found應該是string::size_type。這可能是你的問題,因爲int是有符號的而size_t是無符號的。有關更多信息,請參閱string::npos

非營利組織是一個靜態成員恆定值 與 size_t類型的元素的最大可能值。

編輯:

感謝Martin的評論我換成size_tstring::size_type

+0

啊謝謝,我已經這樣做了,那麼我必須解決另一個問題,並忘記改變它。 – Matt 2011-06-06 03:03:01

+0

根據我的標準npos(和查找)副本有std :: string :: size_type類型std :: string :: size_type – 2011-06-06 03:24:18

+0

@Martin:這很奇怪我一直用它作爲size_t – GWW 2011-06-06 03:25:35

2

如果您所看到的問題是,你的程序總是打印1,2,3,......而不是正確的行號,那是因爲你只增加lineCount如果子被發現;修復它將lineCount++移至if(found != string::npos)區塊之後。

如果根本沒有看到任何輸出,則該文件不包含" hello "(大小寫很重要,而且這些空格字符不會與其他空白字符匹配),或者「test.txt」不在其中正確的地方或名稱錯誤。

注:foundstring::npos之間的比較是確定在這裏(儘管一個是簽署int,另一個是size_t(可能是64位系統上unsigned int或可能unsigned long long),有趣的是,這將打破,如果你。將found更改爲unsigned intsize_t恰好是更寬的無符號類型(在32位計算機上,您可以通過使foundunsigned short來模擬此情況)。由於您實際上未使用found的值,因此最好完全避免轉換,只是做if (s.find(key) != string::npos)