AccountInfo::AccountInfo(QString name, QString accountNumber, QString password, QString imagePath, QStringList friendname) { this->accountName = name; this->accountNumber = accountNumber; this->password = password; this->imagePath = imagePath; this->friendname += friendname; } void AccountInfo::addAccount() { QString fileName = "accountInfo.txt"; QFile file(fileName); if (file.open(QIODevice::Append | QIODevice::Text)) { QTextStream out(&file); // 将好友昵称使用特殊字符分隔 QString friendnameString = friendname.join(";"); out << accountName << "," << accountNumber << "," << password << "," << imagePath << "," << friendnameString << endl; file.close(); } qDebug() << "Add account success"; } 这是accountInfo类的构造函数和一个把信息存进文件的函数,每一行是一个账户,写一个在指定账户(名字)后添加新朋友的函数
时间: 2024-04-18 07:30:27 浏览: 94
你可以在AccountInfo类中添加一个函数来实现在指定账户后添加新朋友的功能。以下是一个示例函数:
```cpp
void AccountInfo::addFriend(const QString& accountName, const QString& newFriend)
{
QString fileName = "accountInfo.txt";
QFile file(fileName);
if (file.open(QIODevice::ReadWrite | QIODevice::Text)) {
QTextStream stream(&file);
QStringList lines;
while (!stream.atEnd()) {
QString line = stream.readLine();
QStringList accountInfo = line.split(",");
if (accountInfo.length() >= 5 && accountInfo[0] == accountName) {
// 添加新朋友到好友列表
QStringList friendList = accountInfo[4].split(";");
friendList.append(newFriend);
accountInfo[4] = friendList.join(";");
line = accountInfo.join(",");
}
lines.append(line);
}
file.resize(0);
for (const QString& line : lines) {
stream << line << endl;
}
file.close();
}
qDebug() << "Add friend success";
}
```
这个函数会打开存储账户信息的文件,然后遍历每一行,找到与指定账户名匹配的行。如果找到匹配的账户名,它会将新朋友添加到好友列表中,并更新该行的内容。最后,它会将更新后的信息写回文件。请确保在使用此函数之前已经创建了AccountInfo类的实例。
阅读全文