替换txt文件c ++中的行 [英] Replace line in txt file c++
问题描述
我只是想知道因为我在 accounts.txt
中有一个包含 STATUS:USERID:PASSWORD 的文本文件。示例如下:
OPEN:bob:askmehere:
OPEN:john:askmethere:
LOCK:rob:robmypurse:
我有一个用户输入在我的主要,因为这样的用户可以登录3x else status将从OPEN更改为LOCK
$ b
OPEN:bob:askmehere:
OPEN:john:askmethere:
LOCK:rob:robmypurse:
之后:
OPEN:bob:askmehere:
LOCK:john:askmethere:
LOCK:rob:robmypurse:
我所做的是:
void lockUser(Accounts& in){
//帐户类包含3个属性(string userid,string pass,status)
ofstream oFile;
fstream iFile;
string openFile =accounts.txt;
string status,userid,garbage;
帐户toupdate;
oFile.open(openFile);
iFile.open(OpenFile);
while(!iFile.eof()){
getline(iFile,status,':');
getline(iFile,userid,':');
getline(iFile,garbage,'\\\
');
if(userid == in.getUserId()){
toupdate.setUserId(in.getuserId());
toupdate.setPassword(in.getPassword());
toupdate.setStatus(LOCK);
break;
}
//这里我应该更新account.txt我该怎么做?
ofile.open(openFile);
ofile<< toupdate.getStatus()<<:<< toupdate.getUserId():<< toupdate.getPassword()< :<< endl;
}
使用ReadLine你想替换,并使用替换替换你想替换的东西。例如写:
string Example =Text to find;
openFile =C:\\accounts.txt; //文件的路径
ReadFile(openFile,Example);
或
#include< fstream>
#include< iostream>
#include< string>
int main(){
ifstream openFile;
string ExampleText = BOB;
openFile(accounts.txt);
openFile>> ExampleText;
openFile.replace(Example,Hello);
}
I just wondering cause i have a text file containing STATUS:USERID:PASSWORD in accounts.txt
example it would look like this:
OPEN:bob:askmehere:
OPEN:john:askmethere:
LOCK:rob:robmypurse:
i have a user input in my main as such user can login 3x else status will change from OPEN to LOCK
example after 3 tries of john
before:
OPEN:bob:askmehere:
OPEN:john:askmethere:
LOCK:rob:robmypurse:
after:
OPEN:bob:askmehere:
LOCK:john:askmethere:
LOCK:rob:robmypurse:
what i have done is:
void lockUser(Accounts& in){
// Accounts class consist 3 attributes (string userid, string pass, status)
ofstream oFile;
fstream iFile;
string openFile="accounts.txt";
string status, userid, garbage;
Accounts toupdate;
oFile.open(openFile);
iFile.open(openFile);
while(!iFile.eof()){
getline(iFile, status, ':');
getline(iFile, userid, ':');
getline(iFile, garbage, '\n');
if(userid == in.getUserId()){
toupdate.setUserId(in.getuserId());
toupdate.setPassword(in.getPassword());
toupdate.setStatus("LOCK");
break;
}
//here i should update the account.txt how do i do that?
ofile.open(openFile);
ofile<<toupdate.getStatus()<<":"<<toupdate.getUserId()":"<<toupdate.getPassword()<<":"<<endl;
}
Use ReadLine and find the line you wanna replace, and use replace to replace the thing you wanna replace. For example write:
string Example = "Text to find";
openFile="C:\\accounts.txt"; // the path of the file
ReadFile(openFile, Example);
OR
#include <fstream>
#include <iostream>
#include <string>
int main() {
ifstream openFile;
string ExampleText = BOB;
openFile("accounts.txt");
openFile >> ExampleText;
openFile.replace(Example, "Hello");
}
这篇关于替换txt文件c ++中的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!