【发布时间】: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++ 中无法实现您想要的字母。经典
C可以非常有效地完成这项工作(但这是一场噩梦)。您仍然可以在C++程序集中使用C代码。所以如果你被允许这样做,你可以看看tutorialspoint.com/cprogramming/c_file_io.htm 和tutorialspoint.com/c_standard_library/c_function_fseek.htm 再一次,这是一场噩梦,我不建议你通过fseek的东西。