2012-09-07 42 views
1

下面我有一個代碼,它讀取一個文本文件,只寫入一行到另一個文本文件,如果它有"unique_chars"字。例如,我也在該行上有其他垃圾。 "column"我怎樣才能用"wall"等其他東西替代短語"column"讀取文本文件和輸出字符串

因此,我行會像<column name="unique_chars">x22k7c67</column>

#include <iostream> 
#include <fstream> 

using namespace std; 

int main() 
{ 

    ifstream stream1("source2.txt"); 
    string line ; 
    ofstream stream2("target2.txt"); 

     while(std::getline(stream1, line)) 
     { 
      if(line.find("unique_chars") != string::npos){ 
      stream2 << line << endl; 
       cout << line << endl; 
      } 

     } 


    stream1.close(); 
    stream2.close();  

    return 0; 
} 
+0

你忘了包括'' Rapptz

+1

看看[串的'replace'功能(http://en.cppreference.com/W/CPP /串/ basic_string的/替換)。 – jrok

回答

1

要做到可以使用的std :: string的方法「替換」替換,它需要一個開始和結束位置和字符串/令牌,將帶您刪除什麼像這樣的地方:

(你也忘了包括在你的代碼串標頭)

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

using namespace std; 

int main() 
{ 
    ifstream stream1("source2.txt"); 
    string line; 
    ofstream stream2("target2.txt"); 

    while(getline(stream1, line)) 
    { 
     if(line.find("unique_chars") != string::npos) 
     { 
      string token("column "); 
      string newToken("wall "); 
      int pos = line.find(token); 

      line = line.replace(pos, pos + token.length(), newToken); 
      stream2 << line << endl; 
      cout << line << endl; 
     } 
    } 

    stream1.close(); 
    stream2.close();  

    system("pause"); 
    return 0; 
} 
2

如果您要更換你能實現自己的replaceAll函數的字符串的所有事件。

void replaceAll(std::string& str, const std::string& from, const std::string& to) { 
    if(from.empty()) 
     return; 
    size_t pos = 0; 
    while((pos = str.find(from, pos)) != std::string::npos) { 
     str.replace(pos, from.length(), to); 
     pos += to.length(); 
    } 
} 
相關問題