-->

C++ Finding a line from a text file and updating/w

2019-06-14 06:01发布

问题:

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

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 :)

回答1:

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.

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 :)