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;
}
5
  • 2
    To start with, don't do while (!input_file.eof()), instead do while (getline(...)) Commented Aug 9, 2013 at 8:19
  • Secondly, you might want to use replace instead of your own replacement code. Commented Aug 9, 2013 at 8:21
  • Could explain why (regarding you first comment)? Commented Aug 9, 2013 at 8:22
  • See e.g. this answer of mine from yesterday. Commented Aug 9, 2013 at 8:23
  • Why do you use fstream instead of ifstream for input stream? Commented Aug 9, 2013 at 8:23

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.