首页 > 解决方案 > C++ 把一个词换成另一个词

问题描述

我想写一个工具来把这个词换成另一个,我给!它已经匹配了某天,并且一直存在我的话被切断或有问题的问题。然后我想要一个使用 std :: regex 的更好的程序,但我不能再处理这个问题了..

#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();
}

标签: c++replacetxt

解决方案


尝试更多类似的东西:

#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();
}

推荐阅读