c++ - 将字符串添加到文件而不覆盖以前的字符串

标签 c++ string file

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

这是我的第一个程序。

    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);

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

如果您遇到困难,请自己尝试第二部分并发布问题,包括您目前的代码。

关于c++ - 将字符串添加到文件而不覆盖以前的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20053787/

相关文章:

html - 如何将文本输入保存为 HTML 和 Django 中的文件

javascript - JS 检查输入字符串是否为有效代码并运行输入

c++ - 在特定时间运行 C++ 循环

c++ - 如何创建 Min STL priority_queue?

C++ 命名空间帮助

java - 替换字符串中的反斜杠

javascript - 使用数组元素替换多次出现的字符串

c - stat.h 在 Linux 中不可用?

python - 为什么 os.rename() 在 Python 2.7 中引发异常?

c++ - 使用管道 Win32 连续读取/写入数据