【发布时间】:2015-01-23 10:19:18
【问题描述】:
我只是想知道,因为我在 accounts.txt
中有一个包含 STATUS:USERID:PASSWORD 的文本文件示例如下:
打开:bob:askmehere:
打开:john:askmethere:
LOCK:rob:robmypurse:
我的主目录中有一个用户输入,因为这样的用户可以登录 3 次,否则状态将从 OPEN 变为 LOCK
john
3 次尝试后的示例之前:
打开:bob:askmehere:
打开:john:askmethere:
LOCK:rob:robmypurse:
之后:
打开:bob:askmehere:
LOCK:john:askmethere:
LOCK:rob:robmypurse:
我所做的是:
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;
}
【问题讨论】:
-
要么读入整个文件,并在内存中替换合适的单词,要么将文件中的光标放到正确的位置,然后替换那里的单词。
-
不要这样做
while (!iFile.eof())因为除非你小心,否则它不会像你期望的那样工作。原因是eofbit标志直到在您尝试从文件之外读取时才设置,从而导致循环迭代一次到多次。相反,例如while (std::getline(...))