【问题标题】:I cant delete single line from a text file C++我无法从文本文件 C++ 中删除单行
【发布时间】:2017-05-24 05:33:39
【问题描述】:

你好,我正在做一个项目,我有学生他们的数字姓名姓氏和所有东西,我想按姓名选择一个学生并删除有关学生的全部信息,它是案例 3:我的代码:`

case 3:{


           int fNomer;
           string ime;
           string prezime;
           string familiq;
           string fakyltet;
           string specialnost;
           int grypa;
           int kyrs;
           string stud;
           cout << "Stydenta koito iskate da iztriete";
           cin >> stud;
           ifstream file;
           ofstream outfile;
           file.open("Student.txt");
           outfile.open("newM.txt");
           while (getline(file, line))
           {
               if (line == deleteMovie){}
               else { outfile << line << endl; }
           }
           outfile.close();
           file.close();
           outfile.close();
           file.close();
           remove("Students.txt");
           rename("newM.txt", "Students.txt");
           break;
}

【问题讨论】:

  • 您应该正确格式化您的代码。例如,就像在您的 C++ 教科书中一样。
  • 欢迎来到 StackOverflow。请采取tour,学习提出好问题stackoverflow.com/help/how-to-ask,制作minimal reproducible example。 MCVE 应包括各种样本输入(说明所有方面)和所需的输出。如果您正在寻求有关调试代码的帮助,请参阅ericlippert.com/2014/03/05/how-to-debug-small-programs MCVE 将提供有关例如什么是 deleteMovie 的信息。这可能是故障机制的一部分。

标签: c++ string file text structure


【解决方案1】:

问题出在这里:

 while (getline(file, line))
 {
    if (line == deleteMovie){}
    else { outfile << line << endl; }
 }

首先我们正确格式化这段代码:

 while (getline(file, line))
 {
    if (line == deleteMovie)
    {
    }
    else
    {
      outfile << line << endl;
    }
 }

现在我们可以看到(我们可以看到之前是否已经)您正在检查错误的变量 deleteMovie 而不是 stud

    if (line == deleteMovie)

应该是

    if (line == stud)

你仍然需要添加错误检查,例如处理文件无法打开的情况。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-22
    • 2011-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多