簡體   English   中英

將字符串添加到文件而不覆蓋以前的字符串

[英]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功能嗎?

嘗試使用追加文件模式app ,其行為記錄為

所有輸出操作都發生在文件末尾,附加到其現有內容。

ofstream outRegister("account.dat", ios::app);

對於第二個問題,請嘗試使用ifstreamgetline逐行處理文件,檢查行中的第一個單詞是否與目標用戶名匹配。

如果您遇到問題,請自行嘗試第二部分並發布一個問題,包括您的代碼。

嘗試使用追加文件模式應用程序,其行為記錄為

所有輸出操作都發生在文件末尾,附加到其現有內容。

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM