【问题标题】:Why does my delete string attempt fail为什么我的删除字符串尝试失败
【发布时间】:2015-03-13 01:30:19
【问题描述】:

我一直在尝试制作我自己的这个例子:

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;
}

我删除了我所能做的,使它成为实际程序的删节版本,希望我没有编辑任何东西,所以它没有意义。

【问题讨论】:

  • 格式良好的编译代码示例将始终让您在此站点上走得更远。您发布的内容可能存在错误,但我在阅读和猜测缺少哪些代码时遇到了麻烦。
  • delreset == true 是一个只有当 delreset 本身也为真时才为真的条件。所以你可以写while(delreset)
  • 循环在每次迭代时都将delreset设置为true,并且在处理输入文件读取时没有错误,因此循环永远不会停止,即使在找到所需的行之后也是如此。

标签: c++ file temp


【解决方案1】:

更简单的版本:

...  // 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 

使用这种方法,您甚至可以直接写入输出文件。

顺便说一句cin&gt;&gt;delstr; 只需要一个字。它在第一个空格处停止并忽略尾随空格。您可以改用getline(cin, delstr);。

【讨论】:

  • OP 的要求是删除指定的行 AND 后面的行。此代码不执行后者。
  • 测试数据给人的印象是两个编号的行。所以我误解了 "string below the first string" 作为引用的例子。我添加了和 EDIT 行,以删除后面的行。
【解决方案2】:

尝试类似的方法:

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");

【讨论】:

  • 当我调用此代码时,它立即运行并完成,什么也没做
  • 这意味着getline() 无法读取一行,您检查了吗?
猜你喜欢
  • 2015-03-05
  • 2020-08-10
  • 1970-01-01
  • 2011-04-04
  • 1970-01-01
  • 1970-01-01
  • 2014-09-01
  • 2023-02-03
  • 2020-05-26
相关资源
最近更新 更多