I am watching a youtube video from 2020 on how to make login system with c++. I have the exact same code as him but I have 1 error where when I save my first password everything works fine the password and user are saved as ID:1, but when I add another user the ID is set to -858993459. Here's the code, it's only in main.cpp.
#include <iostream>
#include <fstream>
#include <string>
#include <math.h>
#include <sstream>
using namespace std;
class loginManager {
public:
loginManager() {
accessGranted = false;
}
void login() {
cout << "Enter your UserName and Password.\n";
cout << "UserName: ";
cin >> userNameAttempt;
int usrID = retriveFile(userNameAttempt, "users.dat");
if (usrID != 0) {
cout << "Password: ";
cin >> passwordAttempt;
int pswID = retriveFile(passwordAttempt, "passwords.dat");
if (usrID == pswID) {
cout << "Successfull login!\n";
accessGranted = true;
login();
}
else {
cout << "Wrong password!\nTry Again!\n\n";
login();
}
}
else {
cout << "Wrong username!\nTry Again!\n\n";
login();
}
}
void addUser(const string username, const string password) {
if (retriveFile(username, "users.dat") != 0) {
cout << "That username is already in use!" << endl;
return;
}
int id = 1 + getLastID();
saveFile(username, "users.dat", id);
saveFile(password, "passwords.dat", id);
}
int getLastID() {
fstream file;
file.open("users.dat", ios::in);
file.seekg(0, ios::end);
if (file.tellg() == 0) {
return 0;
}
string s;
for (int i = -1; s.find("#") == string::npos; i--) {
file.seekg(i, ios::end);
file >> s;
}
file.close();
s.erase(0, 5);
int id;
istringstream(s) >> id;
return id;
}
int retriveFile(string attempt, const char* pathFile) {
string line;
fstream file;
string currentChar;
long long eChar;
file.open(pathFile, ios::in);
while(1) {
file >> currentChar;
if (currentChar.find("#ID:") != string::npos) {
if (attempt == line) {
file.close();
currentChar.erase(0,4);
int id;
istringstream(currentChar) >> id;
return id;
}
else {
line.erase(line.begin(), line.end());
}
}
else {
istringstream(currentChar) >> eChar;
line += (char)decrypt(eChar);
currentChar = "";
}
if (file.peek() == EOF) {
file.close();
return 0;
}
}
}
void saveFile(string p_line, const char* pathFile, const int& id) {
fstream file;
file.open(pathFile, ios::app);
file.seekg(0, ios::end);
if (file.tellg() != 0) {
file << "\n";
}
file.seekg(0, ios::beg);
for (int i = 0; i < p_line.length(); i++) {
file << encrypt(p_line[i]);
file << "\n";
}
file << "#ID:" << id;
file.close();
}
long long encrypt(int p_letter) {
return powf(p_letter, 7) * 3 - 70;
}
long long decrypt(long long p_letter) {
return powf((p_letter + 70) / 3, 1/7.f);
}
private:
string userNameAttempt;
string passwordAttempt;
bool accessGranted;
};
int main() {
loginManager app;
app.addUser("Something", "Somethingelse");
app.login();
return 0;
}