【问题标题】:How to edit the specific line in a text file?如何编辑文本文件中的特定行?
【发布时间】:2019-09-24 04:39:45
【问题描述】:

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

我尝试使用 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 ”。然后当我打开文件时,记录将是新的。

【问题讨论】:

标签: c++ ifstream ofstream


【解决方案1】:

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

【讨论】:

  • 向量是可选的,如果文件很大,这不是一个好主意。没有它也可以完成这项任务。读入一行,根据需要进行编辑,将其写入新文件,重复直到完成。然后用新文件替换原文件
  • 好的,谢谢。但是我假装用户会打开这个系统很多次,但是我怎样才能每次都将整个东西重写到不同的文件中呢?好吧,我的意思是我不能让程序自己打开一个随机的新文本文件。
  • @HuangMolly 以读取模式打开原始文件名(比如 file_orig)。阅读它并编辑内存中的行。以写入模式打开另一个文件(比如 file_tmp)。将内容/修改后的内容写入 file_tmp。关闭这两个文件。删除file_orig。将 file_tmp 重命名为 file_orig。您可以使用 'std::filesystem::copy' 来复制文件。
猜你喜欢
  • 2012-03-09
  • 2010-12-30
  • 1970-01-01
  • 2011-06-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多