我試圖使用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;
}
運行它在調試器中,看看它出錯的地方。 – 2011-06-06 02:59:54
注意:'string :: find()'不會**返回一個'int'。請使用std :: string :: size_type。 – 2011-06-06 03:20:27
Martin:雖然我更喜歡這種結構,但OP的程序實際上並沒有錯誤地處理最後一行;如果你嘗試在最後一行之後讀取一行,getline將清除字符串。所以總是有一個額外的循環,'s'是空的,但這不會使輸出錯誤。 – 2011-06-06 03:21:00