C ++ Finding a string from a text file and updating / writing a string

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

I used the for loop to find the traverse along the lines. But how do I update it when necessary? (withdrawals and deposits update the balance)

This is the code I have:

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 will happen next? Thank:)

0
source share
1 answer

, , ( ). .

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

. CLARIFYING , , . , :)

+2

Source: https://habr.com/ru/post/1569084/


All Articles