Debugging question 3

The following code looks for a word in a text file and replaces it with another word:
// this code contains errors
// [search and replace a word in a text file]
#include<iostream>
#include<fstream>
#include<string>
int main(int argc, char** argv) {
  using namespace std;
  if (argc < 4) {
    cout << "need a filename, a word and its replacement on cmd line" << endl;
    return 1;
  }
  ifstream ifs(argv[1]);
  if (!ifs) {
    cout << "cannot open file " << argv[1] << endl;
    return 2;
  }
  string s;
  while(!ifs.eof()) {
    ifs >> s;
    if (ifs.eof()) {
      break;
    }
    if (s == argv[2]) {
      cout << argv[3];
    } else {
      cout << s;
    }
    cout << " ";
  }
  cout << endl;
  ifs.close();
  return 0;
}
Test it on the folling file, called story.txt, with the command \fbox{\tt ./debug3 story.txt wolf teddy-bear} :
This is just a stupid little story with no meaning whatsoever. The wolf
came out of his den and chased little red hood, found her and pounced on 
her. Little red hood cried, "the wolf!", just stepped aside and the 
wolf cracked his neck on the pavement, his brain in pulp. 
She was to hear of him no more.
The output is:

This is just a stupid little story with no meaning whatsoever. The teddy-bear
came out of his den and chased little red hood, found her and pounced on her. 
Little red hood cried, "the wolf!", just stepped aside and the 
teddy-bear cracked his neck on the pavement, his brain in pulp. She was to 
hear of him no more.
Note that one occurrence of the word ``wolf'' was not actually changed to ``teddy-bear''. Fix this problem.



Subsections

Leo Liberti 2008-01-12