Answers
Program code to copy:-
#include <iostream> //Used for standard input/output
#include <cstdlib> //used for exit() function
#include <fstream> //used for input file stream
using namespace std;
//Function prototype
int searchList(int stdList [], int numElems, int searchValue);
int main()
{
//Decalring array to store data set read from standard file
int stdArray[100];
//Decalring array to store data set read from test file
int testArray[50];
//Decalring input file stream object
ifstream stdFile, testFile;
//Open the standard file for reading
stdFile.open("LSStandard.txt");
//Checking whether the file is opened successfully or not
if(!stdFile)
{
cout << "LSStandard.txt file can not opened for reading" << endl;
exit(0);
}
int i=0;
//Loop will be executed till end of file
while(!stdFile.eof())
{
//Reading each number from standard file into array
stdFile >> stdArray[i];
i++;
}
//Closing standard file
stdFile.close();
//Storing total numbers read from standard file
int numElemsStd = i;
//Open the test file for reading
testFile.open("LSTest.txt");
//Checking whether the file is opened successfully or not
if(!testFile)
{
cout << "LSTest.txt file can not opened for reading" << endl;
exit(0);
}
i=0;
//Loop will be executed till end of file
while(!testFile.eof())
{
//Reading each number from test file into array
testFile >> testArray[i];
i++;
}
//Closing test file
testFile.close();
//Storing total numbers read from test file
int numElemsTest = i;
int index;
for(int i=0; i<numElemsTest; i++)
{
//Calling function for each element of test array to search it in standard array
index = searchList(stdArray, numElemsStd, testArray[i]);
if(index != -1)
{
//Display details of each number of test array if found in an standard array
cout << "Number " << (i+1) << " " << "(" << testArray[i] << ")"
<< " was located at index " << index << endl;
}
else
{
//Display details of each number of test array if not found in an standard array
cout << "Number " << (i+1) << " " << "(" << testArray[i] << ")"
<< " was not in the file" << endl;
}
}
return 0;
}
//Function search for searchValue within the stdList array and
//return one of two answers: -1 if value is not in stdList array or
//if searchValue is in stdList, the index position of searchValue within the stdList array.
//Function accepts three parameters:-
//1. An array that contains the standard data set.
//2. The parameter numElems is the number of elements in that array.
//3. The parameter searchValue is the element that we are searching for.
int searchList(int stdList[], int numElems, int searchValue)
{
for(int i=0; i<numElems; i++)
{
if(stdList[i]==searchValue)
//Returns index value of number if found in standard array
return i;
}
//Returns -1 if not found in standard array
return -1;
}
Screenshot of output:-
Screenshot of content of file named "LSStandard.txt" used in the program:-
Screenshot of content of file named "LSTest.txt" used in the program:-