Question

Hi I how do i use a vector to search a array for a string that...

Hi I how do i use a vector to search a array for a string that user has enter into the console. here is some of the instructions for the programing I am trying to work on

The purpose of this program is to write a class whose job is to read up to 10,000 names into a string array. The class sorts the names and then the user can ask the class to find full names containing a name as either a first name or a last name. For example, if the user wanted to find “JOHN” You will write a NameSearch class that will read the file, sort the names, and provide the user with a way to search the list for either first or last names. Two vectors of strings are declared in main and passed by reference to the class. The class will fill vectors for the first name or the last name.

here is the header file for reference
#ifndef _NAMESEARCH_H
#define _NAMESEARCH_H

#include
#include
#include
#include
using namespace std;

class NameSearch{

   private:
       //holds names read from file

       array names;

       int total = 0;       /*total number of names read from file,
                       class will read up to 10,000,
                       stops reading after 10,000th.*/

                       /*NOTE: do not assume you'll have 10,000 in the file
                       Your program should work with 10 items or 10005 items in file.
                       Test program with files with <10,000, 10,000 and >10,000*/

       string name;       //user's requested name to look for in the list
       string filename;   //the name of the file that is read

       bool bReady =false;   //true if file read successfully
                       //false if file not read successfully

       void ReadFile();   //reads the file, fills names array and sorts data
                           //assigns total & bReady

       void Sort();       //sorts the array names in place

   public:
       //void ReadFile();
      
       //Two constructors, be sure to initialize data appropriately
       NameSearch();           //no file, does not try to read anything      
       explicit NameSearch(string fName);   //is passed desired file, calls readFile()

       void SetFileName(string fName);   //is passed desired file
                                           //calls readFile()

       bool IsReady();       /*returns bReady flag. The programmer *should* check
                           this before attempting to search for a name. The finds
                           are designed to anticipate no data just in case*/

                           /* find functions are passed a reference to a vector and a string. Each looks
                           for the name, and fill the vectors with the full names containing that name.
                           The name searching algorithm is performed in the find functions.
                           Programming note: if name is not found, the find returns a false and the vector
                           contains no names.*/

       bool FindFirstNames(vector &vsFirst, string name);
       bool FindLastNames(vector &vsLast, string name);

       int GetTotal();   //returns the total number read from the file.
                       //if the file hasn't been read or was not read successfully,
                       //returns a -1

};

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Source code:-

//here i can't add input text file it's as per your requirement which file you want to test just add the file name in the readfile() function inside the NameSearch.cpp.

NameSearch.cpp:-

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <fstream>
#include "NameSearch.h"
#include "P3_TemplateSort.h"
#include "Functions.h"

using namespace std;

void Header()
{
   cout << "Chegg \n Answer \nThe NameSearch Class \n" << endl;
}

NameSearch::NameSearch()   //default constructor
{
   for(int i = 0; i < 10000; ++i)
       {
           names[i] = " ";
       }
   total = 0;
  
}

NameSearch::NameSearch(string fName)   //is passed desired file, calls readFile()
{
   filename = fName;
  
   for(int i = 0; i < 10000; ++i)
       {
           names[i] = " ";
       }
   total = 0;
  

}

void NameSearch::ReadFile() // opens file and reads data into an array
{
   ifstream openFile;

   openFile.open(filename);     // in place of filename you can enter your file name with proper address.

   if(!openFile)
   {
       bOpen = false;
       total = -1;
   }
   // Read the file
   int i = 0;
   while( !openFile.eof() )
   {
       getline(openFile, names[i]);
       total++; //counts the number of lines
       i++;
      
   }

   // Finsihed reading the file, close the file.
   openFile.close();
   sort();
   bOpen = true;
}

void NameSearch::setFileName(string fName)
{
   filename = fName;
   ReadFile();
}

bool NameSearch::isOpen()
{
   return bOpen;
}

bool NameSearch::findFirstNames(vector<string> &vsFirst, string sName)
{
   name = "";
   vsFirst.clear();
   for (unsigned int h = 0; h < sName.length(); ++h)
   {
       name += toupper(sName[h]);
   }
   for (int i = 0; i < total; ++i)
   {
       int pos = names[i].find(' ');
       int final = names[i].find(name,pos);
       if (final >= 0)
       {
           vsFirst.push_back(names[i]);
       }
   }
   if (vsFirst.size() > 0)
   {
       return true;
   }
   else
   {
       return false;
   }
}

bool NameSearch::findLastNames(vector<string> &vsLast, string sName)
{
   name = "";
   vsLast.clear();
   for (unsigned int h = 0; h < sName.length(); ++h)
   {
       name += toupper(sName[h]);
   }
   for (int i = 0; i < total; ++i)
   {
       int pos = names[i].find(' ');
       int final = names[i].rfind(name,pos);
       if (final >= 0)
       {
           vsLast.push_back(names[i]);
       }
   }
   if (vsLast.size() > 0)
   {
       return true;
   }
   else
   {
       return false;
   }
  
}

int NameSearch::getTotal()
{
   return total;
}

void NameSearch::sort()
{
   TemplateSort<string> sort;
   sort.shellSort(names,total);

}

------------------------------------------------------------------------------------------------------------------

NameSearch.h:-

#ifndef _NAMESEARCH_H
#define _NAMESEARCH_H

#include <string>
#include <vector>
using namespace std;

class NameSearch
{
private:
   string names[10000];   //holds names read from file

   int total;       /*total number of names read from file,
                   class will read up to 10,000,
                   stops reading after 10,000th.*/
                  
       /*NOTE: do not assume you'll have 10,000 in the file
       Your program should work with 10 items in file.
       Test program with files with <10,000, 10,000 and >10,000*/

   bool bOpen;   //true if file read successfully
                   //false if file not read successfully

   void ReadFile();   //reads the file, fills names array and sorts data
                       //assigns total & bOpen
                      
   void sort();       //uses the sorter provided to you to sort the names array

   string name;       //user's requested name to look for in the list
   string filename;   //the name of the file that is read

public:

   //Two constructors, be sure to initialize data appropriately
   NameSearch();           //no file, does not try to read anything      
   NameSearch(string fName);   //is passed desired file, calls readFile()

   void setFileName(string fName);   //is passed desired file
                                       //calls readFile()

   bool isOpen();       /*returns bOpen flag. The programmer *should* check
                       this before attempting to search for a name. The finds
                       are designed to anticipate no data just in case*/
  
   /* find functions are passed a reference to a vector and a string. Each looks
   for the name, and fill the vectors with the full names containing that name.
   The name searching algorithm is performed in the find functions.
   Programming note: if name is not found, the find returns a false and the vector
   contains no names.*/

   bool findFirstNames(vector<string> &vsFirst, string name);
   bool findLastNames(vector<string> &vsLast, string name);

   int getTotal();   //returns the total number read from the file.
                   //if the file hasn't been read or was not read successfully,
                   //returns a -1
  
};

#endif

-------------------------------------------------------------------------------------------------------

Functions.h:-

#include <iostream>
using namespace std;
void Header();

-------------------------------------------------------------------------------------------------------------

P3_TemplateSort.h:-

//How to use this class
//First, #include "P3_TemplateSort.h" in the file where the sort is needed.

//here i already add in your class NameSearch.cpp

#ifndef _TEMPLATESORT_H
#define _TEMPLATESORT_H

template <class X> class TemplateSort
{
public:
   TemplateSort();
   void shellSort(X arr[], int size);
};

template <class X>
TemplateSort<X>::TemplateSort()
{

}
template <class X>
void TemplateSort<X>::shellSort(X arr[], int size)
{
   int h = 1;
        /*
         * find the largest h value possible
         */
    while ((h * 3 + 1) < size)
   {
       h = 3 * h + 1;
   }

    /*
     * while h remains larger than 0
     */
    while( h > 0 )
   {
        /*
         * for each set of elements (there are h sets)
         */
        for (int i = h - 1; i < size; i++)
       {
            /*
             * pick the last element in the set
             */
            X B = arr[i];
            int j = i;
            /*
             * compare the element at B to the one before it in the set
             * if they are out of order continue this loop, moving
             * elements "back" to make room for B to be inserted.
             */
            for( j = i; (j >= h) && (arr[j-h] > B); j -= h)
           {
                arr[j] = arr[j-h];
            }
            /*
             * insert B into the correct place
             */
            arr[j] = B;
        }
        /*
         * all sets h-sorted, now decrease set size
         */
        h = h / 3;
    }

}

#endif

Add a comment
Know the answer?
Add Answer to:
Hi I how do i use a vector to search a array for a string that...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • INPUT FILE INTO ARRAY. CHECKING FOR COMMAS AND SUCH. HOW TO DO? PLEASE READ CAREFULLY. MAX_SIZE...

    INPUT FILE INTO ARRAY. CHECKING FOR COMMAS AND SUCH. HOW TO DO? PLEASE READ CAREFULLY. MAX_SIZE is size of array When iterating over the candidates’ list, do not iterate over the entire array, but just over the records where data is filled in void readFile(Candidate candidates[]) – reads the elections.txt file, fills the candidates[] array. Hint: use substr() and find() functions. Set Score to 0. void List(Candidate candidates[]) – prints the array of Candidate structs. One candidate per one line,...

  • SortAndSearch.cpp – Objectives: Binary Search and Selection sort You are given a list of 20 names...

    SortAndSearch.cpp – Objectives: Binary Search and Selection sort You are given a list of 20 names as follows: {"Collins, Bill", "Smith, Bart", "Michalski, Joe", "Griffin, Jim",                         "Sanchez, Manny", "Rubin, Sarah", "Taylor, Tyrone", "Johnson, Jill",                         "Allison, Jeff", "Moreno, Juan", "Wolfe, Bill", "Whitman, Jean",                         "Moretti, Bella", "Wu, Hong", "Patel, Renee", "Harrison, Rose",                   "Smith, Cathy", "Conroy, Pat", "Kelly, Sean", "Holland, Beth"}; Write a program to sort and display the names in alphabet order (use selection sort). The program prompts...

  • Stuck on this computer science assignment Write a program that demonstrates binary searching through an array...

    Stuck on this computer science assignment Write a program that demonstrates binary searching through an array of strings and finding specific values in an corresponding parallel double array. In all cases your output should exactly match the provided solution.o. Provided files: Assignment.cpp - starter assignment with function prototypes companies.txt - file for program to read. earnings.txt - file for program to read. Input1.txt Input2.txt - Test these inputs out manually, or use stream redirection Input3.txt - These inputs are based...

  • // Name.h #ifndef __NAME_H__ #define __NAME_H__ #include <iostream> #include <string> using namespace std; #define MAXLENGTH 12...

    // Name.h #ifndef __NAME_H__ #define __NAME_H__ #include <iostream> #include <string> using namespace std; #define MAXLENGTH 12 #define NAME_CHARS "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-'" namespace Errors {     struct InvalidName { }; } class Name { public:     Name        ( string first_name = "", string last_name = "");     string first() const;     string last() const;     void   set_first( string fname );     void   set_last( string lname);     friend ostream& operator<< ( ostream & os, Name name );     friend bool operator== (Name name1, Name...

  • In c++ please How do I get my printVector function to actually print the vector out?...

    In c++ please How do I get my printVector function to actually print the vector out? I was able to fill the vector with the text file of names, but I can't get it to print it out. Please help #include <iostream> #include <string> #include <fstream> #include <algorithm> #include <vector> using namespace std; void openifile(string filename, ifstream &ifile){    ifile.open(filename.c_str(), ios::in);    if (!ifile){ cerr<<"Error opening input file " << filename << "... Exiting Program."<<endl; exit(1); }    } void...

  • Must be written in C++ Display results and comments Write a program that sorts a vector...

    Must be written in C++ Display results and comments Write a program that sorts a vector of names alphabetically using the selection sort and then searches the vector for a specific name using binary search. To do that, you need to write three functions: 1. void selSort (vector <string> & v): sorts the vector using selection sort 2. void display (const vector <string> & v): displays the vector contents 3. int binSearch (const vector <string> & v, string key): searches...

  • in c++ Program 1 Write a program that sorts a vector of names alphabetically using the...

    in c++ Program 1 Write a program that sorts a vector of names alphabetically using the selection sort and then searches the vector for a specific name using binary search. To do that, you need to write three functions I. void selSort (vector string &v: sorts the vector using selection sort 2. void display (const vector <string & v): displays the vector contents . int binSearch (const vector <ing& v, string key): searches the vector for a key returns the...

  • Files given in this assignment (right-click on the file to download) Assignment7.cpp (need to complete) Student.h...

    Files given in this assignment (right-click on the file to download) Assignment7.cpp (need to complete) Student.h (Given. Just use it, don't change it!) Student.cpp (Partially filled, need to complete) 1. Assignment description In this assignment, you will write a simple class roster management system for ASU CSE100. Step #1: First, you will need to finish the design of class Student. See the following UML diagram for Student class, the relevant header file (class declaration) is given to you as Student.h,...

  • This lab is to give you more experience with C++ Searching and Sorting Arrays Given a...

    This lab is to give you more experience with C++ Searching and Sorting Arrays Given a file with data for names and marks you will read them into two arrays You will then display the data, do a linear search and report if found, sort the data, do a binary search. Be sure to test for found and not found in your main program. Read Data Write a function that reads in data from a file using the prototype below....

  • I need an OUTLINE ONLY (pseudocode/comments). DO NOT DO THE PROGRAMMING ASSIGNMENT. Part I: PA3 Outline...

    I need an OUTLINE ONLY (pseudocode/comments). DO NOT DO THE PROGRAMMING ASSIGNMENT. Part I: PA3 Outline (10 points). Create an outline in comments/psuedocode for the programming assignment below. Place your comments in the appropriate files: main.cpp, functions.h, dealer.cpp, dealer.h, dealer.cpp (as noted below). Place into a file folder named LastnamePA3, the zip the content and hand in a zip file to Canvas. Part II: PA3: Car Dealership (40 points) For Programming Assignment 3 you will be creating a program to...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT