Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/127.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++替换文件文本-不工作_C++_Fstream - Fatal编程技术网

C++替换文件文本-不工作

C++替换文件文本-不工作,c++,fstream,C++,Fstream,我试图通过搜索用户名来创建一个更改密码函数,如果找到确认密码,如果为true,则用newPass替换密码 文件是这样写的:USERNAME;密码 我用它来替换字符串,但不确定它的语法是否正确 tempPass.replace(0, tempPass.length(), newPass); 这是我目前的代码: void AccountManager::changePassword(AccountManager & account) { string username, passw

我试图通过搜索用户名来创建一个更改密码函数,如果找到确认密码,如果为true,则用newPass替换密码

文件是这样写的:USERNAME;密码

我用它来替换字符串,但不确定它的语法是否正确

tempPass.replace(0, tempPass.length(), newPass); 
这是我目前的代码:

void AccountManager::changePassword(AccountManager & account) {
  string  username, password, newPass, passwordConf, tempUser, tempPass;
  fstream openFile("UserPass.txt", ios_base::out | ios_base::in | ios_base::app);

  // / Check if username exsists.
  do {
    cout << "Enter your username: " << endl;
    getline(cin, username);
    cout << "Enter you current password: " << endl;
    getline(cin, password);

    if (account.UserPass[username] != password) {
      cout << "Username and password do not match. " << endl;
    }
  } while (account.UserPass[username] != password);

  do {
    cout << "Enter new password: " << endl;
    getline(cin, newPass);
    cout << "Retype password: " << endl;
    getline(cin, passwordConf);

    if (newPass != passwordConf) {
      cout << "Password does not match confirmation. " << endl;
    }
  } while (newPass != passwordConf);

  // /find / replace password with newPass in file
  while (!openFile.eof()) {
    getline(openFile, tempUser, ';');
    getline(openFile, tempPass);

    if ((tempUser == username) && (tempPass == password)) {
      ofstream openFile("UserPass.txt", ios_base::app);

      tempPass.replace(0, tempPass.length(), newPass);    // changes pass in file at index ;+1
      cout << "Password has been changed. " << endl;
      switchLog(account);                                 // Login on successful password change.

      break;
    }
  }
  account.UserPass[username] = newPass;
}

谢谢,

您可以通过查找文件的位置,然后用完全相同的字节数替换数据来解决问题,但是不鼓励这样做,除非文件非常大,并且替换的数据量非常小

编辑文件内容的正确方法是:

读取文件的全部内容 对内存中读取的数据执行修改 将修改后的数据写入新文件 删除旧文件
阅读了解更多详细信息。

可以使用ostream在文件的任何位置写入。想一想seekp。你能指导我在append中编辑的方向吗?因为我的情况只是为了学习?至于制作新文件和复制所有内容,我如何在不破坏整个程序的情况下做到这一点?替换名称?请查看编辑后的答案,如果您觉得有帮助,请将其标记为正确。我需要的是我的情况下的语法,而不是它是否可以完成。不过我非常感谢你的帮助,泰。