-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
135 lines (99 loc) · 2.68 KB
/
main.cpp
File metadata and controls
135 lines (99 loc) · 2.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
// Check if username already exists
bool userExists(const string &username) {
ifstream fin("users.txt");
string line, fileUser;
if (!fin) return false;
while (getline(fin, line)) {
if (line.empty()) continue;
size_t pos = line.find(':');
if (pos == string::npos) continue;
fileUser = line.substr(0, pos);
if (fileUser == username) {
return true;
}
}
return false;
}
// Registration function
void registerUser() {
string username, password;
cout << "Enter username: ";
getline(cin, username);
cout << "Enter password: ";
getline(cin, password);
if (username.empty() || password.empty()) {
cout << "Error: Fields cannot be empty!\n";
return;
}
if (username.length() < 3 || password.length() < 3) {
cout << "Error: Minimum 3 characters required!\n";
return;
}
if (userExists(username)) {
cout << "Error: Username already exists!\n";
return;
}
ofstream fout("users.txt", ios::app);
if (!fout) {
cout << "Error: File cannot be opened!\n";
return;
}
fout << username << ":" << password << endl;
cout << "Registration successful!\n";
}
// Login function
bool loginUser() {
string username, password, line;
string fileUser, filePass;
cout << "Enter username: ";
getline(cin, username);
cout << "Enter password: ";
getline(cin, password);
ifstream fin("users.txt");
if (!fin) {
cout << "Error: No user database found!\n";
return false;
}
while (getline(fin, line)) {
if (line.empty()) continue;
size_t pos = line.find(':');
if (pos == string::npos) continue;
fileUser = line.substr(0, pos);
filePass = line.substr(pos + 1);
if (fileUser == username && filePass == password) {
cout << "Login successful!\n";
return true;
}
}
cout << "Invalid username or password!\n";
return false;
}
int main() {
int choice;
do {
cout << "\n1. Register\n";
cout << "2. Login\n";
cout << "3. Exit\n";
cout << "Enter choice: ";
cin >> choice;
cin.ignore();
switch (choice) {
case 1:
registerUser();
break;
case 2:
loginUser();
break;
case 3:
cout << "Exiting program...\n";
break;
default:
cout << "Invalid choice!\n";
}
} while (choice != 3);
return 0;
}