Hi,
I'm working on a small project and i'm stuck in a part where I need to replace the existing word in file with a new one. I really have no idea about it.. I'm posting the function block where i'm facing the problem

void team::team_list()
{
    string str = "(team)";  //existing word
    string strTemp;
    string tname;          // to be placed in file
    cout<<"\n\n"<<"\t\t\t"<<"Enter the team name: ";
    cin.sync();
    getline(cin,tname,'\n');
    tname += ".doc";
    fstream file(tname.c_str());
    CopyFile("D:\\C++\\proj\\team.doc",tname.c_str(),TRUE);
    file.close();
    ifstream second(tname.c_str(), ios::in);
    while(!second.eof())
    {
        if(strTemp == str)           // I'm facing problem here
          second<<tname;
    }
    dept_stud();
}

I hope I find the solution for this problem soon!!
thank You!!

Recommended Answers

All 2 Replies

Does this really need to be part of a separate program? If you just need to replace the first occurrence of a word in some file before you use the file for something else, then you could use "sed" like this:

your_prompt> sed -i s/OldWord/NewWord/ path_to_File.extension

In this example, capitalization matters and only the first occurrence will be replaced. However, since sed uses regular expressions, it could be made case insensitive and also set up to replace every occurrence. The -i option makes the operation take place in-line (that is, it directly modifies the specified file). If you want the output in a new file, leave off the -i option and pipe the output to a new file:

your_prompt> sed s/OldWord/NewWord/ path_to_File.extension >> SomeNewFile.extension

Once you get it working, the whole thing can be wrapped up in a shell script and executed just like any other program.

I know that this was not really an answer to your question, but it is another way to approach the problem and it's very elegant. There is a caveat though. sed is standard equipment on linux/unix, but is missing from Windows. There is however a Windows implementation available on SourceForge.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.