Question: Need to upgrade the program below to include FileIO. Get user input for the filename, and then read the names from the file and form
Need to upgrade the program below to include FileIO. Get user input for the filename, and then read the names from the file and form the last name string.
HINT: You need to use getLine() for reading the file and perhaps for reading the filename from the keyboard.
#include #include #include #include
using namespace std;
int Menu(); void getName(vector &names, int &count); int removeName(vector &names, int count, string list); void displayName(vector &names, int count); int findName(vector &names, int count, string list); void sortName(vector &names, int count); string getLastNames(vector &names, int count);
int main() { vector names; int count = 0; int choice = Menu(); while (choice != 0) { switch (choice) { case 1: { getName(names, count); } break; case 2: { string name; cout << "Enter name to remove: "; getline(cin, name); int x = removeName(names, count, name); if (x == -1) { cout << "Name is not in the list" << endl; } else { count = x; } } break; case 3: { displayName(names, count); } break; case 4: { string name; cout << "Enter name to find: "; getline(cin, name); int num = findName(names, count, name); if (num == -1) { cout << "Name not found in the list" << endl << endl; } else { cout << "Name found at number " << num << " in the list." << endl << endl; } } break; case 5: { sortName(names, count); } break; case 6: { cout << getLastNames(names, count) << endl; } break; case 0: { return 0; } break; } choice = Menu(); } return 0; }
void getName(vector &names, int &count) { string name; cout << "Enter name: "; getline(cin, name); int pos = name.find(' '); if(pos != -1) { string first = name.substr(0, pos); string last = name.substr(pos+1); name = last + "," + first; } names.push_back(name); count++; }
int Menu() { int choice; cout << "1. Add a name" << endl; cout << "2. Remove a name" << endl; cout << "3. Display names " << endl; cout << "4. Search a name" << endl; cout << "5. Sort names" << endl; cout << "6. Show all Last Names" << endl; cout << "0. Quit" << endl; cout << "Enter a option: "; cin >> choice; while (choice < 0 || choice > 6) { cout << "Choice not on list: "; cin >> choice; } cin.ignore(); return choice; }
string getLastNames(vector &names, int count) { stringstream ss; for (int i = 0; i void sortName(vector &names, int count) { for (int i = 0; i names[j]) { string temp = names[i]; names[i] = names[j]; names[j] = temp; } } } for (int i = 0; i < count; i++) { cout << names[i] << endl; } }
int findName(vector &names, int count, string list) { for (int i = 0; i int removeName(vector &names, int count, string list) { int find = findName(names, count, list); if (find == -1) return find; for (int i = find; i void displayName(vector &names, int count) { if (count == 0) { cout << "No names to display" << endl; return; } for (int i = 0; i