0
#include <iostream>
#include <fstream> 

using namespace std;

bool isLoggedIn(){
    string username, password, name, pass;
    cout << "Enter username: "; cin >> username;
    cout << "Enter password: "; cin >> password;

    ifstream readf(username + ".txt");
    getline(readf, name); // line 1
    getline(readf, pass); // line 2

    if(name == username && pass == password){
        return true;
    } else{
        return false;
    }
}

int main()
{
    int choice;
    cout << "1. Register | 2. Login\nChoose: "; cin >> choice;

    if(choice == 1){
        string username, password;
        cout << "Create username: "; cin >> username;
        cout << "Create password: "; cin >> password;

        ofstream file; // HERE, i am declaring the name of the file
        file.open(username + ".txt"); // then am opening the file
        file << username << endl << password; // writing 
        file.close(); // then closing it, but its not actually doing anything?

        main();
    } else if(choice == 2){
        bool status = isLoggedIn(); 

        if(!status){
            cout << "Login failed" << endl;
            system("pause");
            return 0; // since main() is int., 0 = false
        } else {
            cout << "Login successful" << endl;
            system("pause");
            return 1; // 1 = true
        }
    }

}

I have no idea why the file is not being created, I dont think i need to specifically tell it where to create the file, since there are no errors, i am very new in c++ so i would appreciate it if you can thoroughly explain what the issue is, and maybe how can i clean up my code, thank you!

Iso
  • 93
  • 2
  • 5
  • `main();` ? Recursively calling main is not valid C++. That should have been a loop. Anyway, to your question, try adding error handling to the code. [Example](https://stackoverflow.com/questions/28342660/error-handling-in-stdofstream-while-writing-data). It's also possible that it didn't fail, it just created the file somewhere you don't expect. In that case, `chdir`. –  May 25 '21 at 11:16
  • Calling `main` in C++ has undefined behaviour. Also, returning zero from `main` conventionally indicates success, and everything else indicates failure. – molbdnilo May 25 '21 at 11:33
  • You say "there are no errors", but your code doesn't do any error checking. You should at least check that the file is valid after `open`. Also, your current directory may not be what you think it is depending on how you run this. – interjay May 25 '21 at 11:52

0 Answers0