-1

I want to write a tool to change the word to another one, as I give! It matches that already some day and all the time there is a problem that my word is cut off or something is wrong. then I want a better program with the use of std :: regex but I can't cope with this problem anymore ..

#include <iostream>
#include <fstream>
void display_members()
{
    std::string oldWord;
    std::string newWord;
    std::string tmp;
    std::string getcontent;
    std::ifstream openfile ("test", std::ios::in | std::ios::app);
    std::cin >> oldWord;
    std::cin >> newWord;
    // if(openfile.is_open())
    // {
        while(! openfile.eof())
        {
            getline(openfile,tmp);
            while((tmp.find(oldWord)) != std::string::npos)
            {
                tmp.replace(tmp.find(oldWord),newWord.length(),newWord);
            }
            std::cout << ","<<tmp << " " << " ";
                // openfile >> getcontent;
                // std::cout << getcontent<< " ";
        }
       
    // }
     openfile.close();
}
int main()
{
   display_members();
}

user207421
  • 305,947
  • 44
  • 307
  • 483
Eriss69
  • 69
  • 5
  • `while(! openfile.eof())` -> `while(getline(openfile,tmp)) { ... }` What isn't working for you? What is some sample input where there's a problem? Why do you open the file in append mode? – Retired Ninja Jan 05 '21 at 03:06
  • If your code is not working, you *must* provide a sample input and output for what the code *should* do. – cigien Jan 05 '21 at 03:09
  • my code works, but cuts off the next word after replacing it – Eriss69 Jan 06 '21 at 17:24

1 Answers1

0

Try something more like this instead:

#include <iostream>
#include <fstream>

void display_members()
{
    std::string oldWord, newWord, tmp;
    std::string::size_type pos;

    std::cin >> oldWord;
    std::cin >> newWord;

    std::ifstream openfile("test");
    while (getline(openfile, tmp))
    {
        pos = 0;
        while ((pos = tmp.find(oldWord, pos)) != std::string::npos)
        {
            tmp.replace(pos, oldWord.length(), newWord);
            pos += newWord.length();
        }
        std::cout << "," << tmp << " " << " ";
    }
}

int main()
{
    display_members();
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770