create a running database C++ program.
Can add, search, or delete a record.
#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;
}
Comments
Leave a comment