#include <iostream>
#include <fstream>
#include <string>
using namespace std;
// Function prototypes
bool isUserExist(const string& username, const string& password);
void registerUser(const string& username, const string& password);
void loginUser();
int main() {
int choice;
do {
cout << "1. Register\n";
cout << "2. Login\n";
cout << "3. Exit\n";
cout << "Enter your choice: ";
cin >> choice;
switch (choice) {
case 1: {
string username, password;
cout << "Enter username: ";
cin >> username;
cout << "Enter password: ";
cin >> password;
registerUser(username, password);
break;
}
case 2:
loginUser();
break;
case 3:
cout << "Exiting program.\n";
break;
default:
cout << "Invalid choice. Try again.\n";
}
} while (choice != 3);
return 0;
}
bool isUserExist(const string& username, const string& password) {
ifstream file("users.txt");
string line;
while (getline(file, line)) {
size_t pos = line.find(',');
string storedUsername = line.substr(0, pos);
string storedPassword = line.substr(pos + 1);
if (username == storedUsername && password == storedPassword) {
file.close();
return true;
}
}
file.close();
return false;
}
void registerUser(const string& username, const string& password) {
ofstream file("users.txt", ios::app);
file << username << ',' << password << '\n';
file.close();
cout << "User registered successfully.\n";
}
void loginUser() {
string username, password;
cout << "Enter username: ";
cin >> username;
cout << "Enter password: ";
cin >> password;
if (isUserExist(username, password)) {
cout << "Login successful.\n";
} else {
cout << "Invalid username or password.\n";
}
}