C ++从文本文件中查找行并更新/编写该行 [英] C++ Finding a line from a text file and updating/writing the line

查看:128
本文介绍了C ++从文本文件中查找行并更新/编写该行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个程序应该能够读取的银行帐户文件.到目前为止,使用ifstream可以使用此功能.但是我希望程序读取文本文件的第六行(其值为"balance"),然后根据需要对其进行更新(删除并替换为新值).

I have a bank account file that the program should be able to read. This function works as of now with the use of ifstream. But I want the program to read the 6th line of the text file (which has the value 'balance') and then update it as needed (delete and replace with new value).

我使用了for循环来查找遍历行.但是,如何在需要时更新? (提款和存款会更新余额)

I used a for loop to find traverse through the lines. But how do I update it when needed? (Withdrawal and deposit of money updates the balance)

这是我现在拥有的代码:

This is the code I have for now:

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

接下来的人们会怎样? 谢谢:)

What comes next folks? Thanks :)

推荐答案

如果您的文件非常小(如前所述),则可以将其带入字符串数组(每行文本一个元素).然后对数组进行更改,然后将整个数组重新写回到文件中.

If your file is very small like you've mentioned, you may bring it into an array of strings (one element per line of text). Then make changes to the array and re-write the whole array back to the file.

例如,您可以将其读入arrya中,如下所示:

For example, you can read it into an arrya like this:

//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();
  }

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

I did not test this but I think it's ok. More code: If you add the following bit of code at the end of your main code, you should see the contents from the array. And if this shows nothing that clearly means that your file is EMPTY.

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

注意:尽管我想为您提供有关该论坛的澄清问题的帮助,但我认为这个问题超出了该论坛的范围.也许您需要花一些时间来学习循环和其他结构的技巧:)

Note: While I'd like to help you out on CLARIFYING issues on this forum, I think this question is going beyond the nature of this forum. Perhaps what you need is to spend some time learning the art of loops and other structures :)

这篇关于C ++从文本文件中查找行并更新/编写该行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆