在文本文件中搜索和替换

时间:2016-03-27 20:29:53

标签: c++ search replace fstream

我正在尝试在文本文件中进行搜索和替换,但它不起作用,我知道它的简单感觉就像我错过了一些小东西。我正在尝试用非空格字符替换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; 
}

2 个答案:

答案 0 :(得分:0)

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;
}

答案 1 :(得分: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");