[英]Adding strings to files without overwriting the previous strings
我有兩個問題。 我正在研究基於文件的問題。
這是我的第一個程序。
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";
每次運行此代碼時,我的progrm都會從用戶獲取數據並存儲在“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功能嗎?
嘗試使用追加文件模式應用程序,其行為記錄為
所有輸出操作都發生在文件末尾,附加到其現有內容。
ofstream outRegister("account.dat", ios::app);
您可以使用:
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";
這段代碼可以正常工作。 因為你是以追加模式打開文件( ios_base::app
)實際上std::ofstream
構造函數的原型是( string, std::ios_base::openmode
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.