Im trying to use the string::find method to determine if the string ” hello ” (with space before and after) exists in a line of a .txt file. if it does, its supposed to print out the line number(position isnt important). the problem is, its not finding the string. please help.
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;
}
What it seems to be doing as you have it is just counting the number of lines that have that string in them. You should increment the line number var in every iteration of the loop, not just when the string is found.