gpt4 book ai didi

c++ - 使用C++删除linux文本文件中的行

转载 作者:行者123 更新时间:2023-11-30 05:48:46 25 4
gpt4 key购买 nike

我需要有关如何在 Linux 中使用 C++ 编写代码来执行删除行的帮助。下面列出了我在文本文件中的内容

description:amount:date
electricity bill:100:25jan2015
telephone bill:100:25jan2015
telephone bill:50:25jan2015

我想这样做,以便当用户选择选项 b 以删除用户输入的费用并防止程序删除重复数据时,用户将必须输入金额和日期。谢谢。

而 temp.txt 用于存储在重命名为 Expense.txt 之前未删除的内容,因此如果电话费值 100 被删除,它将变为

electricity bill:100:25jan2015
telephonebill:50:25jan2015

void deleteexpensesdata(string& expense, string& texpense, double& amount,  string& date){
int check, x=0;
ifstream Expenses("Expense.txt");
ofstream temp("temp.txt");
cout << "\n";
cout << "Enter Type of Expense you wish to remove" << endl;
cin >> texpense;

while(Expenses >> expense >> amount >> date){
if(texpense!=expense){//if there are expenses with different name, input their data into temp file
temp << expense << ":" << amount << ":" << date <<endl;
}
if(texpense==expense){// if user entered correct name, x=1 for later output message that the user data has been deleted
x=1;
}
}

Expenses.clear();
Expenses.seekg(0, ios::beg);
Expenses.close();
temp.close();
remove("Expense.txt");
rename("temp.txt","Expense.txt");
if(x==0){//x was set to 0 at start, so if it didn't change, it means there is error
cout << "Remove of Expense failed" << endl;
}
else{//if x is not = 0 then remove is successful
cout << "Expenses has been removed" << endl;
}
}

调用函数的代码如下

        cout << "Remove Expense.\n";
deleteexpensesdata(expense, texpense, amount, date);
cout << "Expense Date has been delete. \n" << endl;
cin.ignore();
cin.get();

最佳答案

下面的代码获取用户输入并将 double 转换为字符串并将所有 3 个变量转换为带有分隔符“:”的行,如您的示例输入所示,在您打开文件后,您会得到不匹配的行一个临时文件并重命名该文件,基本上将其删除。

double expamt;
string line, expdesc, exptrans;
cout << "Please Enter Expense: \n";
cin >> expdesc;
cout << "Please Enter Amount: \n";
cin >> expamt;
string newamt = static_cast<ostringstream*>( &(ostringstream() << expamt) )->str();
cout << "Date of Transaction: (e.g 20jan2015)\n";
cin >> exptrans;

string input = expdesc + ":" + newamt + ":" + exptrans;

ifstream myfile;
ofstream tempfile;
myfile.open("Expense.txt");
tempfile.open("temp.txt");
while (getline(myfile, line))
{
if (line != input)
tempfile << line;
}
cout << "\nExpense " << expdesc << " has been removed \n" <<endl;
myfile.close();
tempfile.close();
remove("Expense.txt");
rename("temp.txt", "Expense.txt");

关于c++ - 使用C++删除linux文本文件中的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28062055/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com