Changing information in a specific spot in a file

I have a text file, let's call it "words.txt"

words.txt reads exactly as follows:

line1 word1 word2 word3
line2 word1 word2 word3
line3 word1 word2 word3

I have a function that initializes a line depending on user input so that they are as follows:

1
2
3
4
5
6
string var1, var2, var3, var4;
var1 = line[cin];
var2 = word1;
var3 = word2;
var4 = word3;
//not the code, just the result of initializer 


Say I wanted to change word2 on line2 to whatever the user inputs there, say "baloney":

line1 word1 word2 word3
line2 word1 baloney word3
line3 word1 word2 word3

What's the best way of going about that?
Last edited on
Excluding the very special case where changes result in no change to the length (or encoding) of a word, you basically have to
- read in each line in turn.
- decide if you need to change the line in some way.
- write out the (possibly modified) line to a new temporary file.

When you're done, you can then decide to
- rename the original file to say 'file.bak', then rename the temporary to file.txt
- Forego the backup, and just replace file.txt with the newly created temporary.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <string>
using namespace std;


template<typename M> void printIt( const M matrix )
{
   for ( auto &row : matrix )
   {
      for ( auto e : row ) cout << e << " ";
      cout << '\n';
   }
}


int main()
{
   string line, word;
   vector< vector<string> > page;
   ifstream in( "words.txt" );
   while( getline( in, line ) )
   {
      stringstream ss( line );
      vector<string> vline;
      while ( ss >> word ) vline.push_back( word );
      page.push_back( vline );
   }

   cout << "Before:\n";
   printIt( page );

   int row = 2, col = 2;
   page[row-1][col-1] = "Brexit";

   cout << "\nAfter:\n";
   printIt( page );
}


Before:
word1 word2 word3 
word1 word2 word3 
word1 word2 word3 

After:
word1 word2 word3 
word1 Brexit word3 
word1 word2 word3 
Topic archived. No new replies allowed.