Answer to Question #350705 in C++ for nana

Question #350705

create a running database  C++ program.

Can add, search, or delete a record.


1
Expert's answer
2022-06-15T07:07:15-0400
#include <iostream>
#include <vector>
#include <string>

using namespace std;

string awk(string query, string delim, size_t start, size_t end);
void db_search(vector<string> db, string str);
void usage();

int main()
{
    vector<string> database;
    vector<string>::iterator found;
    string query, prompt;
    usage();
    getline(cin, query);

    do {
        if (awk(query, " ", 0, 1) == "add") {
            query = awk(query, "\"", 1, 2);
            database.push_back(query.substr(1, query.size()));
        } else if (awk(query, " ", 0, 1) == "search") {
            query = awk(query, "\"", 1, 2);
            db_search(database, query.substr(1, query.size()));
        } else if (awk(query, " ", 0, 1) == "delete") {
            query = awk(query, "\"", 1, 2);
            found = find(database.begin(), database.end(), query.substr(1, query.size()));
            if (found != database.end()) {
                cout << "Found record: " << *found << "\nDelete? (Yes/No) ";
                cin >> prompt;
                if (prompt == "Yes") {
                    database.erase(found);
                }
            }
        } else if (awk(query, " ", 0, 1) == "exit") {
            return 0;
        }
        getline(cin, query);
    } while (true);
    return 0;
}

string awk(string query, string delim, size_t start, size_t end) {
    size_t part = 0, p_start = 0;
    while (part != start) {
        p_start = query.find(delim);
        part++;
    }
    size_t p_end = p_start + 1;
    while (part != end) {
        p_end = query.find(delim, p_end+1);
        part++;
    }
    p_end -= p_start;
    return query.substr(p_start, p_end);
}

void db_search(vector<string> db, string str) {
    for (int i = 0; i < db.size(); i++) {
        if (db[i].find(str) != std::string::npos) {
            cout << db[i] << "\n";
        }
    }
}

void usage() {
    cout << "Usage:" << "\n";
    cout << "add \"Example record\"   \t\t" << "Add record to database\n";
    cout << "search \"rec\"           \t\t" << "Search record\n";
    cout << "delete \"Example record\"\t\t" << "Delete record from database\n" << endl;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
APPROVED BY CLIENTS