Question

I'm trying to check whether the user has valid account number and password(both are integer type) in C++. The data is stored in a .dat file using a structure. This is what I've tried yet:

void printIntroMenu();
void printMainMenu();
void start();
void login();
void createAccount();

char menuInput;
int i=0;
struct user{
int user_id;
int password;
}u;


int main()
{
start();

return 0;
}

void start()
{
cout<<"\n\n";
cout<<setw(60)<<" Please select an option from the menu below:";
printIntroMenu();
cin>>menuInput;
switch(menuInput)
{
     case 'l': login();
     break;
     case 'c': createAccount();
     break;
     case 'q': exit(0);
     break;
     default: cout<<"\n\n Wrong Choice!! Valid choices are l,c or q.";
     start();
}
}
void createAccount()
{
ofstream fout;
fout.open("abc.dat",ios::app|ios::binary);
cout<<setw(60)<<"\n\n Please enter your username (Integer only)";
cin>>u.user_id;
cout<<setw(60)<<"\n\n Please enter your password (Integer only)";
cin>>u.password;
fout<<u.user_id<<'\n'<<u.password<<'\n';
fout.close();
cout<<setw(60)<<"\n Thank You!! Your Account Has Been Successfully Created.";
start();
}
void login()
{
int flag=0;
 int uid;
 int pass;
ifstream fin("abc.dat",ios::in | ios::binary);
cout<<setw(50)<<"Enter your username: ";
cin>>uid;
cout<<setw(50)<<"Enter your password: ";
cin>>pass;
while(!fin.eof())
{
    fin.read((char*)&u,sizeof(user));
    if(u.user_id==uid && u.password==pass)
    {
        flag=1;
        cout<<"\n Login Successful!!";
    }
    else{
        cout<<setw(60)<<"*************** LOGIN FAILED! ***************";
    start();
    }
}

}

Whatever I enter as input in the login menu, I always get Login failed as output. Please tell me if there is any problem in the structure of storing the data or retrieval of data from the file or Is there anything that I'm missing in the code.

Was it helpful?

Solution

You forget string to number conversion, because this

fin.read((char*)&u,sizeof(user));

won't get you what you want, it gets numbers from file in char* format, not int.

It should be done this way:

fin >> u.user_id;
fin >> u.password;

OTHER TIPS

You need to have a flag as well. If the record is not there at the first location it may show 'login failed' but the record might exist at second location. So keep a flag variable. If the flag variable hasn't been updated after traversal through the entire file, then print 'login failed'.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top