我一直试图制作我自己的这个例子版本:
Delete a specific line from a file
但我不能让我的工作正常。我目前的程序目标是删除字符串及其信息(这是第一个字符串下面的字符串),它的作用是什么;但是,它还为第一行添加了一个额外的空间,使它看起来像这样:
(First Line)
(Second Line) This should be the first line.
以下是代码:
infile = ifstream;
outfile = ofstream;
cout<< "What string would you like to delete";
cin>>delstr;
infile.clear();
infile.seekg(0, ios::beg);
ofstream tempfile;
tempfile.open("temp.txt",std::ios::app);
while(delreset == true){
if(delstr == fLine){
getline(infile, fLine);
cout<<"String deleted.\n";
delreset = false;
while(fLine != nothing){
getline(infile, fLine);
tempfile<<fLine<<"\n";
}
tempfile.close();
infile.close();
outfile.close();
remove("example.txt");
rename("temp.txt","example.txt");
}else{
tempfile<<fLine<<endl;
getline(infile, fLine);
}
outfile.flush();
delreset = true;
}
我删除了我可以使它成为实际程序的删节版本,希望我没有编辑任何内容以便它没有意义。
答案 0 :(得分:0)
更简单的版本:
... // prepare everything as before
while(getline(infile, fLine)) {
if(delstr == fLine) { // if line found do nothing
cout<<"String deleted.\n";
getline(infile, fLine); // EDIT: and read and ignore the following line
}
else
tempfile<<fLine<<"\n"; // else copy it
}
... // here infile was read and tempfile contains the filtered output
使用这种方法,您甚至可以直接写入outfile。
顺便说一句,cin>>delstr;
只能说一句话。它在第一个空白处停止并忽略尾随空白。您可以使用getline(cin, delstr);
代替。
答案 1 :(得分:0)
尝试更像这样的东西:
cout << "What string would you like to delete";
getline(cin, delstr);
bool deleted = false;
infile.clear();
infile.seekg(0, ios::beg);
ofstream tempfile;
tempfile.open("temp.txt", std::ios::app);
while (getline(infile, fLine))
{
if ((!deleted) && (fLine == delstr))
{
getline(infile, fLine);
cout << "String deleted." << endl;
deleted = true;
}
else
tempfile << fLine << endl;
}
tempfile.close();
infile.close();
outfile.close();
if (deleted)
{
remove("example.txt");
rename("temp.txt", "example.txt");
}
else
remove("temp.txt");