文件IO - 删除包含特定字符串C ++的一行文本

时间:2014-07-28 01:23:04

标签: c++

我编写了一个读取文本文件的函数,允许用户选择要删除的帐户并删除指定的帐户。我现在需要做的是从文本文件中删除列出其帐户的文本行。删除帐户有什么用处,但仍会显示在帐户列表中,对吧?以下是我的代码。发生的情况是帐户列表文本文件的全部内容被删除,而不仅仅是具有特定帐号的行。实际删除帐户的文本文件工作正常,只是删除了给我带来麻烦的那一行文本。谢谢你的帮助!

void UserInfo::deleteAccount() {
    vector<string> accounts;
    string line;
    char answer;
    ifstream acctList("accountList.txt");

    if (acctList.fail()) {
        cout << "There is a problem opening the file.\n";
        exit(1);
    }
    //populate vector with the list of accounts and display them.
    while (getline(acctList, line)) {
        accounts.push_back(line);
    }
    for (unsigned int i = 0; i < (accounts.size()); i++) {
        cout << accounts[i] << endl;
    }

    cout << "\nEnter the account number of the account you would like to delete: ";
    cin >> acctNo;

    cout << "Are you sure you want to delete account number " << acctNo << "? ";
    cin >> answer;

    const char * result = (acctNo + ".txt").c_str(); //convert the selection choice to a c-string
    if (answer == 'y' || answer == 'Y') {

        if (remove(result) != 0)
            cout << "Unable to delete account." << endl;
        else
            cout << "\nThe account has been deleted successfully." << endl;
        //delete the account name and number from the list of accounts

        //temporary file to store the new list of accounts

        ofstream out("newAcctList.txt", ios::app);

        while (getline(acctList, line)) {
            if (line != acctNo)
                out << line << "\n";

            acctList.close();
            out.close();
            // delete the original file
        }
        if(out){
            remove("accountList.txt");
            // rename old to new
            rename("newAcctList.txt", "accountList.txt");
        } else {
            cout << "Error on output" << endl;
        }
    }//end if

1 个答案:

答案 0 :(得分:0)

您已经在第一个acctList循环中看过while,所以当您再次尝试阅读out时,它已经在最后。您可以迭代vector accounts - 丢弃匹配acctNo的条目(应该是本地变量BTW) - 而不是重新读取文件。