我有两个问题。我正在处理一个基于文件的问题。
这是我的第一个程序。
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";
每次我运行这段代码时,我的程序都会从用户那里获取数据并将其存储在“account.dat”文件中,但会覆盖之前的数据。我如何编写我的程序以将它们写入下一行?
我的第二个问题是,
每当我需要登录时,我需要我的程序从“account.dat”文件中搜索用户提供的特定用户名和密码。如果匹配,它应该允许访问。
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";
}
我的第二个编码正确吗?如果不正确,谁能指导我如何正确使用 getline 函数?
最佳答案
尝试使用附加文件模式 app
,其行为记录为
All output operations happen at the end of the file, appending to its existing contents.
ofstream outRegister("account.dat", ios::app);
对于第二个问题,请尝试使用 ifstream和 getline逐行处理文件,检查行中的第一个单词是否与您的目标用户名匹配。
如果您遇到困难,请自己尝试第二部分并发布问题,包括您目前的代码。
关于c++ - 将字符串添加到文件而不覆盖以前的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20053787/