【问题标题】:C++ Finding a line from a text file and updating/writing the lineC++ 从文本文件中查找一行并更新/写入该行
【发布时间】:2013-05-20 21:19:27
【问题描述】:

我有一个程序应该能够读取的银行帐户文件。这个函数现在可以使用 ifstream 来工作。但我希望程序读取文本文件的第 6 行(其值为“balance”),然后根据需要对其进行更新(删除并替换为新值)。

我使用了一个 for 循环来查找遍历的行。但是我如何在需要时更新它(取款和存款更新余额)

这是我现在拥有的代码:

ifstream file;
string line;
file.open ("accounts.txt", ios::in); 

for(int i = 0; i < 6; ++i)    //6 being the 6th line
      {
         getline(file, line);
      }

接下来会发生什么? 谢谢:)

【问题讨论】:

  • 你的文件有多大?
  • 这是一个小文本文件,大约10行

标签: c++ file text updating


【解决方案1】:

如果您的文件像您提到的那样非常小,您可以将它放入一个字符串数组中(每行文本一个元素)。然后对数组进行更改并将整个数组重新写入文件。

例如,您可以将它读成这样的 arrya:

//assuming you've defined the array A
for(int i = 0; i < 6; i++)    //NOTE: I've changed the loop counter i
      {
         getline(file, line);
         A[i] = line;
         cout << A[i] < "\n"; //This is the NEW LINE I wanted you to put
         //If the ABOVE line gives nothing, you ought to check your TXT file.
      }
//Change line 6
A[5] = "555.00";
//Now reopen the file to write
ofstream Account ("accounts.txt");
if (Account.is_open())
  {
    for(i=0;i<6;i++)
       {//NOTE THAT I HAVE INCLUDED BRACES HERE in case you're missing something.
        Account << A[i] << "\n"; //Loop through the array and write to file
       }
    Account.close();
  }

我没有对此进行测试,但我认为没问题。 更多代码:如果您在主代码末尾添加以下代码,您应该会看到数组中的内容。如果这没有显示任何内容,则表明您的文件为空。

for(int i = 0; i < 6; i++)
   {
    cout << A[i] < " This is a row with data\n";
   }

注意:虽然我想帮助您澄清本论坛上的问题,但我认为这个问题超出了本论坛的性质。也许您需要花一些时间学习循环和其他结构的艺术:)

【讨论】:

  • 问题:它擦除A[1]中的每个值直到6,只写入6的值。其他为空
  • 这是一个很好的概念,只要它保留 A[1] 的现有值以及其余的值而不擦除?
  • @PJ_Boy 您的代码中可能有错误。你能告诉我你的第二个for循环中的代码吗?直接贴在评论区
  • for(int i = 0; i
  • 在 cmets 中乱码
猜你喜欢
  • 2018-02-15
  • 2016-02-09
  • 2014-04-23
  • 1970-01-01
  • 1970-01-01
  • 2022-08-17
  • 2013-10-18
  • 2021-12-30
  • 2012-03-09
相关资源
最近更新 更多