我试图使用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