在文本文件中搜索和替换

Search and replace in text file

本文关键字:替换 搜索 文本 文件      更新时间:2023-10-16

我试图在一个文本文件中搜索和替换,但它不起作用,我知道它很简单,感觉就像我错过了一些小东西。我正试图用一个非太空角色来代替Electric。有人能帮我吗?

感谢

#include <string>
#include <fstream>
#include <iostream>
using namespace std; 
    int main() {
    string line; 
    ifstream myfile("test.txt");
    if (!myfile.is_open())
    {
        cout << "cant open";
        return 1;
    }
    ofstream myfile2("outfile.txt");
    std::string str("");
    std::string str2("Electric");
    while (getline(myfile, line))
    {
        std::size_t found = str.find(str2);
        found = str.find("Electric");
        if (found != std::string::npos) {
            str.replace(str.find(str2), str2.length(), "");
            myfile2 << found << "n";
            //std::cout << line << "n";
        }
        //myfile2 << str2 << "n";
    }
        remove("test.txt");
        rename("outfile.txt", "test.txt");
        return 0; 
}

粗溶液:

#ifndef _STREAMBUF_H
#include <streambuf>
#endif

void ReplaceInFile(string inputfile, string outputfile, string replace_what, string replace_with) {
   //Read file into string
    ifstream ifs(inputfile);
    string inputtext((istreambuf_iterator<char>(ifs)),
        istreambuf_iterator<char>());
    ifs.close();

    //Replace string
    size_t replace_count = 0;
    size_t found = !string::npos /*not npos*/;
    while (!(found == string::npos)) {
        found = inputtext.find(replace_what, found);
        if (found != string::npos) {
            ++replace_count;
            inputtext.replace(found, replace_what.length(), replace_with);
        }
    }
    //Output how many replacements were made
    cout << "Replaced " << replace_count, (replace_count == 1) ? cout << " word.n" : cout << " words.n";
    //Update file
    ofstream ofs(outputfile /*,ios::trunc*/); //ios::trunc with clear file first, else use ios::app, to append!!
    ofs << inputtext; //output now-updated string
    ofs.close();
}

示例用法:

ReplaceInFile("tester.txt", "updated.txt", "foo", "bar");
int main()
{
  using namespace std;
  ifstream is( "in.txt" );
  if ( !is )
    return -1;
  ofstream os( "out.txt" );
  if ( !os )
    return -2;
  string f = "Electric";
  string r = "";
  string s;
  while ( getline( is, s ) ) // read from is
  {
    // replace one:
    //std::size_t p = s.find( f );
    //if ( p != std::string::npos )
    //  s.replace( p, f.length(), "" );
    // replace all:
    for ( size_t p = s.find( f ); p != string::npos; p = s.find( f, p ) )
      s.replace( p, f.length(), r );
    os << s << endl; // write to os
  }
  return 0;
}