如何在文本文件中编辑特定行?

时间:2019-09-24 04:39:45

标签: c++ ifstream ofstream

我应该如何编辑文本文件中的特定行?以及如何避免覆盖问题。 (如何保留以前添加的记录,而不是用新记录替换?)

我尝试使用line.replace,但显示“没有匹配的成员函数来调用替换”。

else if(choice == 4){

//            count++;

    string edit;
    string newdate;
    double newincome;
    double newoutcome;
    double EditTodayBalance = 0;
    string emptySpace = "         ";
//            string sentence;

    cout << " There are " << count << " record(s) in the file " <<     endl;
    cout << " Please enter the date to edit " << endl;
    cin >> edit;



    size_t pos;
    ifstream Record("BankRecord.txt");
    if (Record.is_open()) {
        while (getline(Record, line)) {
            pos = line.find(edit);
            if (pos != string::npos) // string::npos is returned if 
string is not found
                {
                    cout << line << endl;

                    cout << " Enter what you want to replace " << endl;

                    cout << " Please enter the new date you want to put " << endl;
                    cin >> newdate;
                    cout << " Please enter the new income you want to put " << endl;
                    cin >> newincome;
                    cout << " Please enter the new outcome you want to put " << endl;
                    cin >> newoutcome;

                    cout << "            Your new Record is                 " << endl;
                    cout << count << emptySpace << newdate << emptySpace << newincome << emptySpace << newoutcome << endl;


                    //line.replace()
            }
        }
    }
    EditTodayBalance = newincome - newoutcome;
    cout << " Today's balance is " << EditTodayBalance << endl;

    cout << " Please reenter your choice " << endl;
    cin >> choice;
}

我希望如果旧行是“ 1 2/2/2019 32 21”,我输入新行是“ 1 2/3/2019 22 11”。然后,当我打开文件时,记录将是新记录。

1 个答案:

答案 0 :(得分:0)

恐怕您将不得不重写整个文件。逐行读取文件的内容,并将其存储在内存中(可能是字符串的向量)。现在,在该向量的指定行上进行编辑。操作完成后,将向量的全部内容转储到另一个文件中。您以后可以替换原始文件。