In: Computer Science
A class Names reads the following names from the .txt file
Name.txt
Jason Butler
Paul Cunningham
Logan Bryant
Cody paul
Robert Vernon Ehlers III
Quincy James Ellefson
Currionte Evans
Gavin Scott French
Zach Tyler Goss
Noah Cosby
Jeremy Whittle
Ryan brown
Jonah Dalton Null
Cameron jones
Xavier Rhodes
Malcom Wesley
Jamarcus johnson
Bernard smith
Joseph Nettles
Danny Willaims
James wellington
William bolar
Make a search directory using dynamic allocation where the user would search the any number of letters of the first name and the matching name/names would come up as output. Write C++ code and pseudocode in a doc file
In order to solve this problem, one should need to know about ifstream, eof, search, and npos.
Name.txt file:
C ++ Code for searching from a text file:
//basic header package to run the program
#include<iostream>
#include<conio.h>
//Name is in string, so add string package
#include<string>
// fstream package is used to run ifstream Myfile that is used to read the file
#include<fstream>
using namespace std;
int main()
{
// search is itself a function object that is inbuilt
string search;
//offset is further used to manipulate or find the characters according to search input
int offset;
//line is itself a Name in text file
std::string line;
//ifstream is stream class to read from files, declaring filename that is Myfile
ifstream Myfile;
//opening the file that is Name.txt
Myfile.open("Name.txt");
//asking the user to enter the Name whatever they want to search
cout<< "Type the name you want to search" <<endl;
//storing the search value that the user input
cin >> search;
//if Name.txt file is open
if(Myfile.is_open())
{
// eof stands for end of file that is in this case last name is the end of file
while(!Myfile.eof())
{
//getline scans the value with space
getline(Myfile, line);
//if line.find is not equal to npos, this means name has been found
if((offset = line.find(search, 0)) != string::npos){
std::cout<< "The Name has been found as: " << line <<endl;
}
}
//closing the Name.txt file
Myfile.close();
}
else
std::cout<<"Could not find the Name" << endl;
//if search name doesn't match in Name.txt names, then system will pause for sometime
system("PAUSE");
return 0;
}
The output of the code if the user searches for the name Jason Butler:
so this is how one can search from a text file.