我正在尝试使用c ++删除文本文件内的一行。例如,我有一个包含文本的.txt文件:
booking.txt
1 jer 34 r er
2 43 45 34 456
3 2 4 5 6
4 45 546 435 34
5 cottage 1 323 23
6 we we r we
7 23 34 345 345
8 wer wer wer we
我想在满足特定条件时删除一行。假设我要删除第三行,则必须从.txt文件中删除ID为3的行。
我的代码:
void DeleteLine(string filename)
{
string deleteline;
string line;
ifstream fin;
fin.open(filename);
ofstream temp;
temp.open("temp.txt");
cout << "Input index to remove [0 based index]: "; //input line to remove
cin >> deleteline;
while (getline(fin, line))
{
line.replace(line.find(deleteline), deleteline.length(), "");
temp << line << endl;
}
temp.close();
fin.close();
remove("cottage.txt");
rename("temp.txt", "cottage.txt");
}
但给我以下结果:
1 jer 4 r er
2 4 45 34 456
2 4 5 6
4 45 546 45 34
5 cottage 1 23 23
当前,您仅删除deleteline
每行中的第一个匹配项。要删除整个行,deleteline
您必须替换
line.replace(line.find(deleteline), deleteline.length(), "");
temp << line << endl;
与
std::string id(line.begin(), line.begin() + line.find(" "));
if (id != deleteline)
temp << line << endl;
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句