gonzato gonzato - 2 months ago 7
C++ Question

C++ Function to Search for A Numeric Value in a File

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)
{
string searchVal;

cout << "\nWhat value would you like to search for?\n";

cin.ignore();
getline(cin, searchVal);

ifstream file; //create input file object that will be read from
file.open(fileName); //"ifstream file (fileName)"

if (!file)
{
cout << "\nUnable to open file.\n";
exit(1);
}

string words;

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;

file.close();
return;
}

else
{
cout << "\nThe value " << searchVal << " was not found.\n";

file.close();
return;
}
}
}


Any help is greatly appreciated

Answer

You need to put the else part out side of while loop. Otherwise your function will only search for the first line.

Comments