I have an assignment where I must create a function that takes a filename as a parameter, opens the file, asks a user to enter a value to be searched for, and then searches the file for that value. The file I was given to use for this assignment is a file with a list of revenue and expense values. I have tried just about everything and keep receiving the "value not found" prompt even when I enter a value that i know is in the file.
The code is
void numberSearch(string fileName)
cout << "\nWhat value would you like to search for?\n";
ifstream file; //create input file object that will be read from
file.open(fileName); //"ifstream file (fileName)"
cout << "\nUnable to open file.\n";
int curLine = 0; //file line counter
while (getline(file, words))
++curLine; //counts each line in the file
if (words.find(searchVal) != string::npos)
cout << "\nLine " << curLine << " contains " << searchVal << endl;
cout << "\nThe value " << searchVal << " was not found.\n";
You need to put the
else part out side of
while loop. Otherwise your function will only search for the first line.