逐行修改c ++中文本文件的内容

时间:2014-04-28 06:20:23

标签: c++

我有一个包含以下行的文本文件

  

f 2533 // 1877 2535 // 1875 2639 // 1959 2629 // 1949

     

f 2641 // 1962 2643 // 1963 2622 // 1812 2215 // 1811

现在我想通过删除“//”并添加一个必须类似

的空格来编辑该文件
  

f 2533 1877 2535 1875 2639 1959 2629 1949

     

f 2641 1962 2643 1963 2622 1812 2215 1811

我如何实现这一点是c ++

1 个答案:

答案 0 :(得分:-2)

#include <iostream> 
#include <fstream> 
#include <string> 

using namespace std; 

ifstream myfile_in ("input.txt"); 
ofstream myfile_out ("output.txt");
string line; 

void find_and_replace( string &source, string find, string replace ) { 

size_t j; 

 for ( ; (j = source.find( find )) != string::npos ; ) { 
     source.replace( j, find.length(), replace ); 
  } 

 myfile_out << source <<endl; 
 cout << source << endl; 
} 

int main () { 

 if (myfile_in.is_open()) 
         { 
        int i = 0,j; 
        //string strcomma ; 
          // string strspace ; 

     while (! myfile_in.eof() ) 
             { 

              getline (myfile_in,line); 

            string strfind= "//"; 
            string strreplacewith = " "; 


            find_and_replace( line , strfind, strreplacewith ); 


          i++; 

       } 

        myfile_in.close(); 

     } 

        else cout << "Unable to open file(s) "; 

        system("PAUSE"); 
        return 0; 
      }