Reputation: 1586
I have two questions. I m working on a problem based on files.
Here is my first program.
ofstream outRegister( "account.dat", ios::out );
if ( !outRegister ) {
cerr << "File could not be opened" << endl;
exit( 1 );}
cout<<"enter your username :";
cin>>a;
cout<<"enter your password :";
cin>>b;
outRegister<<a<<' '<<b;
cout<<"your account has been created";
everytime i run this code, my progrm gets data from user and stores in the "account.dat" file, but by overwriting the previous ones. How can i code my program to write them in the next line?
And my second question is,
whenever i need to login, i need my program to search for that particular username and password given by user from the "account.dat" file.If it matches it should allow accesss.
ifstream inRegister( "account.dat", ios::in );
if ( !inRegister ) {
cerr << "File could not be opened" << endl;
exit( 1 );
}
string a,a1,b,b1;
cout<<"\nyou are a premium user\n\n"<<endl;
cout<<"\n enter your user name:\t";
cin>>a;
while(getline(inRegister,a1))
{
if(a1==a)
{
cout<<"\n enter your password: \t";
cin>>b;
inRegister>>b1;
if(b1==b)
{
cout<<"\n access granted logging in....\n\n";
Allowaccess();
}
else
{
cout<<"\n you have entered a wrong password";
}
}
else
cout<<"\n no such user name is found";
}
is my second coding correct?If not, Can anyone guide me how to use the getline function properly?
Upvotes: 0
Views: 165
Reputation: 3379
you can use:
std::ofstream outRegister("account.dat", std::ios_base::app | std::ios_base::out);
if ( !outRegister ) {
cerr << "File could not be opened" << endl;
exit( 1 );}
cout<<"enter your username :";
cin>>a;
cout<<"enter your password :";
cin>>b;
outRegister<<a<<' '<<b;
cout<<"your account has been created";
This code would would work just fine. Because you are opening the file in append mode (ios_base::app
)
Actually the prototype of std::ofstream
constructor is (string, std::ios_base::openmode
)
Upvotes: 0
Reputation: 42165
Try using the append file mode app
, whose behaviour is documented as
All output operations happen at the end of the file, appending to its existing contents.
ofstream outRegister("account.dat", ios::app);
For your second question, try using ifstream and getline to process the file line by line, checking whether the first word in the line matches your target username.
Try the second part yourself and post a question, including your code to date, if you get stuck.
Upvotes: 2