2011-12-13 28 views
2

在此函數中,我需要替換輸入文件中的所有字符,例如輸入另一個字符,例如a。一個i。我已經給了它兩個鏡頭,但是因爲我是新手,現在想我的大腦甚至不能提供任何建議?從文件中讀取並交換C++中的某個字符

void swapping_letter() 
{ 
ifstream inFile("decrypted.txt"); 

char a; 
char b; 
string line; 

if (inFile.is_open()) 
{ 
    while (!inFile.eof()) 
    { 
     getline(inFile,line); 
    } 

    cout<<"What is the letter you want to replace?"<<endl; 
    cin>>a;    
    cout<<"What is the letter you want to replace it with?"<<endl; 
    cin>>b; 

    replace(line.begin(),line.end(),a,b); 


      inFile<<line 


    inFile.close(); 

} 
else 
{ 
    cout<<"Please run the decrypt."<<endl; 
} 
} 

或:

void swapping_letter() 
{ 
ifstream inFile("decrypted.txt"); 

char a; 
char b; 

if (inFile.is_open()) 
{ 
    const char EOL = '\n';           
    const char SPACE = ' '; 

    cout<<"What is the letter you want to replace?"<<endl; 
    cin>>a;    
    cout<<"What is the letter you want to replace it with?"<<endl; 
    cin>>b; 

    vector<char> fileChars;          
    while (inFile.good())            
    { 
     char c; 
     inFile.get(c); 
     if (c != EOL && c != SPACE)        
     { 
      fileChars.push_back(c); 
     } 


     replace(fileChars.begin(),fileChars.end(),a,b); 

     for(int i = 0; i < fileChars.size(); i++) 
     { 
      inFile<<fileChars[i]; 
     } 
    } 
} 
else 
{ 
    cout<<"Please run the decrypt."<<endl; 
} 
} 

回答

2

一種方法是閱讀原始文件,替換字符,並將輸出寫入到一個新文件。

然後最終當你完成可能用新的覆蓋舊文件。

+0

我沒有這樣做? – Dom

+0

你的權利,我可以替換字符,但是當我試着寫代碼糟透了,生病看看它謝謝! – Dom

4

仔細查看這段代碼:

cout<<"What is the letter you want to replace?"<<endl; 
cin>>a;    
cout<<"What is the letter you want to replace it with?"<<endl; 
cin>>b; 

它讀取字符,不能多不能少。如果你點擊「一個輸入」,你會沒事的,輸入將會是未讀的,但這不會造成任何傷害 - 它會將「a」和「b」讀入兩個變量。但是如果你點擊「輸入b輸入」,它會讀取「a」並輸入兩個變量!

+0

真的嗎?沒有看到這之前抱歉我不能看到,但我怎麼解決這個問題? – Dom

+0

只需輸入「a b enter」而不是「a enter b enter」。或者改變你的代碼來讀取行而不是字符。 –

+0

我在代碼中的第二次鏡頭使用線代替,你呢?我看不出如何用b代替一個值。或者我在棒的錯誤末端? – Dom

2

我會先從相對簡單的解決方案:

  1. 店的文件在vector<char>內容(注意大文件)
  2. 遍歷向量的內容,做掉
  3. 覆蓋舊的文件與向量的內容這樣的
+0

是不是我已經做了第二我得到的功能? – Dom

+0

是的,你有一些接近 – SundayMonday

+0

你可以發現錯誤是在我的代碼?因爲整個晚上都在努力嘗試,而且它不行,腦纔不會工作。是替代()因爲從來沒有爲我工作? – Dom

相關問題