0

Below is the code that is trying to replace two strings in a text file parameters.in, however only the second one of them gets replaced for some reason. The replacement occurs in main() using the function ModifyParametersIn. Can anyone give a hint on how to fix that?

void ModifyParametersIn(string search_string, string replace_string) {
  string inbuf;
  fstream input_file("parameters.in", ios::in);
  ofstream output_file("parameters.out");

while (!input_file.eof()) {
      getline(input_file, inbuf);

      int spot = inbuf.find(search_string);
      if(spot >= 0) {
         string tmpstring = inbuf.substr(0,spot);
         tmpstring += replace_string;
         tmpstring += inbuf.substr(spot+search_string.length(), inbuf.length());
         inbuf = tmpstring;
      }
      output_file << inbuf << endl;

int main() {
...
 string search_string = "start_a0 = " + str_start_a0;
  string replace_string ="start_a0 = " + str_middle_a0;
  cout << search_string << endl;
  ModifyParametersIn(search_string, replace_string);
  search_string = "start_tanb = " + str_start_tanb;
  replace_string = "start_tanb = " + str_middle_tanb;
  ModifyParametersIn(search_string, replace_string);
  cout << search_string<< endl;
return 0;
}
Gleb
  • 53
  • 1
  • 6

1 Answers1

3

Because you open the original file on the second run of ModifyParameterIn and overwrite the output file. Hence, you first change is simply overwritten. You shouldn't open the file in the ModifyParametersIn function, but rather in main. This of course has the problem that the two strings you are trying to replace have to be in the correct order in the file, otherwise, one replacement will also fail.

You could also work some magic to open the file you last wrote to in the function ModifyParametersIn an write it to a new file, leading to a bunch of new files, of which you only use the last one. But that's rather ugly.

arne
  • 4,514
  • 1
  • 28
  • 47