Банкомат с использованием обработки файлов на C ++
Опубликовано: 5 Января, 2022
В этой статье задача состоит в том, чтобы реализовать банкомат с такими функциями, как добавление, удаление, поиск и обновление пользователей с использованием обработки файлов на C ++.
Обработка файлов:
- Обработка файлов используется для хранения вывода программы в файле.
- В C ++ файлы используют три класса fstream, ifstream, ofstream, доступные в файле заголовка fstream для обработки файлов.
Некоторые важные инструкции:
- Пароль для входа в систему администратора - 1234 .
- Первоначально файл пуст, сначала войдите в систему как admin и добавьте пользователя, а затем войдите в систему как пользователь.
Подход:
- Выберите тип пользователя и введите пароль.
- В данном меню выберите основную операцию и введите подробные сведения о таких операциях, как добавление, удаление, поиск и обновление пользователей.
- Выполнив все функции и операции, выйдите из системы банкомата.
- Все файловые операции выполняются в файле с именем aaa.txt , где данные записываются в режиме ofstream и могут быть прочитаны в режиме ifstream.
- После этого файл необходимо закрыть с помощью <filename> .close ().
Ниже представлена реализация описанного выше подхода:
C++
// C++ code to implement an ATM and// its basic functions#include <fstream>#include <iostream>#include <limits>#include <string.h>#include <unistd.h>using namespace std; // Class ATM to get user detailsclass atm {private: char username[30]; int password; int balance; public: char* usernames(void) { // Return username return the username; } int passwords(void) { // Return the password return password; } // Function to get the data void getData(void) { cin.ignore( numeric_limits<streamsize>::max(), "
"); cout << "
Enter username:"; cin.getline(username, 30); cout << "
Enter 4-digit " << "password:"; cin >> password; cin.ignore( numeric_limits<streamsize>::max(), "
"); cout << "
Enter initial" << " balance:"; cin >> balance; cin.ignore( numeric_limits<streamsize>::max(), "
"); } // Function displaying the data void showData(void) { cout << "Username:" << username << ", Password:" << password << ", Balance:" << balance << endl; } // Member Functions int adduser(); int viewallusers(); int deleteuser(char*); void updateuserasdeposit(char*); void updateuseraswithdraw(char*); int searchspecificuser(char*, int); int searchallusertodisplay(char*);}; // Function to implement functionality// of ATM Uservoid atmUser(){ atm a; char uname[30]; int pass, ch, ch1, ch2, found = 0; mainmenu: // System("cls"); cout << "
Welcome to GeeksforGeeks ATM"; cout << "
Login as :
1. Admin
2." << " User
3. " "Exit
Choose one : "; cin >> ch; switch (ch) { case 1: rerun: // System("cls"); cout << "
Enter details to" << " login as Admin
"; cout << "
Enter password:"; cin >> pass; if (pass == 1234) { admin: // System("cls"); cout << "
Welcome to" << " Admin Menu"; cout << "
1. Add User
2." << " Delete User
3. " "View All User
4. " << "Exit"; cout << "
Select one : "; cin >> ch1; switch (ch1) { case 1: a.adduser(); goto admin; case 2: cout << "
Enter the " << "Username to be " "deleted : "; cin.ignore( numeric_limits<streamsize>::max(), "
"); cin.getline(uname, 30); a.deleteuser(uname); goto admin; case 3: a.viewallusers(); // sleep(4); goto admin; case 4: break; } } else { cout << "
Details are " << "incorrect ! Please" " try again"; cin.get(); goto rerun; } goto mainmenu; case 2: // System("cls"); cout << "
Enter details to" << " login as User
"; cin.ignore( numeric_limits<streamsize>::max(), "
"); cout << "Enter username:"; cin.getline(uname, 30); cout << "
Enter password:"; cin >> pass; found = a.searchspecificuser( uname, pass); if (found) { user: // System("cls"); cout << "
Welcome " << uname; cout << "
Welcome to" << " User Menu"; cout << "
1. Deposit
2." << " Withdraw
3. View " "Account
4. " << "Exit
Enter your choice:"; cin >> ch2; switch (ch2) { case 1: a.updateuserasdeposit(uname); goto user; case 2: a.updateuseraswithdraw(uname); goto user; case 3: a.searchallusertodisplay(uname); // sleep(4); goto user; case 4: cout << "Thank you"; break; } } else { cout << "
No account found" << " with username " ":(
Hit ENTER to continue " << uname; cin.get(); } goto mainmenu; case 3: cout << "
Thankyou for " << "banking with " << "GeeksforGeeks"; cin.get(); break; }} // Function to add userint atm::adduser(){ atm a; ofstream file; // Open file in write mode file.open("aaa.txt", ios::out | ios::app); if (!file) { cout << "Error in creating " << "file.." << endl; return 0; } // Read from user a.getData(); // Write into file file.write((char*)&a, sizeof(a)); // Close the file file.close(); return 0;} // View Usersint atm::viewallusers(){ atm a; ifstream file1; // Open file in read mode file1.open("aaa.txt", ios::in); if (!file1) { cout << "Error in opening file.."; return 0; } // Read data from file file1.read((char*)&a, sizeof(a)); while (!file1.eof()) { // Display data on monitor a.showData(); file1.read((char*)&a, sizeof(a)); } // Close the file file1.close(); return 0;} // Function to delete the userint atm::deleteuser(char* uname){ atm a; fstream original, temp; original.open("aaa.txt", ios::in); if (!original) { cout << "
file not found"; return 0; } else { temp.open("temp.txt", ios::out | ios::app); original.read((char*)&a, sizeof(a)); // Till end of file is reached while (!original.eof()) { if (!strcmp(a.usernames(), uname)) { cout << "data found " << "and deleted
" << a.username << "
"; } else { temp.write((char*)&a, sizeof(a)); } original.read((char*)&a, sizeof(a)); } original.close(); temp.close(); remove("aaa.txt"); rename("temp.txt", "aaa.txt"); a.viewallusers(); } return 0;} // Function to update user by// depositing moneyvoid atm::updateuserasdeposit(char* uname){ atm a; fstream file, temp; file.open("aaa.txt", ios::in | ios::out | ios::ate); temp.open("temp.txt", ios::out | ios::app); file.seekg(0); file.read((char*)&a, sizeof(a)); // Till end of the file while (!file.eof()) { if (!strcmp(a.usernames(), uname)) { int b; cout << "
Enter amount " << "to deposit:"; cin >> b; a.balance = a.balance + b; cout << "
Balance is:" << a.balance; temp.write((char*)&a, sizeof(a)); } else { temp.write((char*)&a, sizeof(a)); } file.read((char*)&a, sizeof(a));
РЕКОМЕНДУЕМЫЕ СТАТЬИ |