【问题标题】:Adding strings to files without overwriting the previous strings将字符串添加到文件而不覆盖以前的字符串
【发布时间】:2013-11-18 17:19:30
【问题描述】:

我有两个问题。我正在处理基于文件的问题。

这是我的第一个程序。

    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函数?

【问题讨论】:

    标签: c++ string file


    【解决方案1】:

    尝试使用附加文件模式app,其行为记录为

    所有输出操作都发生在文件的末尾,附加到文件的末尾 现有内容。

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

    对于第二个问题,尝试使用ifstreamgetline 逐行处理文件,检查该行中的第一个单词是否与您的目标用户名匹配。

    如果您遇到困难,请自行尝试第二部分并发布问题,包括您迄今为止的代码。

    【讨论】:

    • 你的意思是,在 while 循环中使用 getline 并检查我的字符串?
    • @JefreeSujit 我在app 模式上添加了更多细节。是的,我的意思是你应该编写一个调用getline 并解析返回的字符串的循环。我在这里也更新了我的答案,使其更加具体。
    • 谢谢..我编写了第二个代码,但卡在了第一个......所以我无法获得。感谢您的帮助。
    • 每一行都包含“用户名[空格]密码”。您需要在空格处拆分行并将用户名与拆分前的行部分进行比较。
    【解决方案2】:

    你可以使用:

    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)

    【讨论】:

      猜你喜欢
      • 2012-01-02
      • 1970-01-01
      • 2015-07-05
      • 1970-01-01
      • 2015-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多