2011-12-15 36 views
0

我有代碼可以工作,但只有一次。我需要輸入字符a與輸入字符b交換。通過循環第一次,它交換了兩個選定的字符,但在第二次和以後的迭代它什麼都不做,但保持outFile相同。我如何才能交換兩個以上的字符,直到我想停止?多次在一個文件中交換字符

ifstream inFile("decrypted.txt"); 
ofstream outFile("swapped.txt"); 

const char exist = 'n'; 
char n = '\0'; 
char a = 0; 
char b = 0; 

cout<<"\nDo u want to swap letters? press <n> to keep letters or any button to continue:\n"<<endl; 
cin>>n; 

while (n != exist)       
{ 
    cout<<"\nWhat is the letter you want to swap?\n"<<endl; 
    cin>>a;    
    cout<<"\nWhat is the letter you want to swap it with?\n"<<endl; 
    cin>>b; 
    if (inFile.is_open()) 
    { 
     while (inFile.good()) 
     { 
      inFile.get(c); 

      if(c == b) 
      { 
       outFile<< a; 
      } 
      else if (c == a) 
      { 
       outFile<< b; 
      } 
      else 
      { 
       outFile<< c; 
      }        
     } 
    } 
    else 
    { 
     cout<<"Please run the decrypt."<<endl; 
    } 

    cout<<"\nAnother letter? <n> to stop swapping\n"<<endl; 
    cin>>n; 
} 

回答

2

考慮一種不同的方法。

收集查找表中的所有字符交換。默認translate['a'] == 'a',輸入字符與輸出字符相同。交換az只需設置translate['a'] = 'z'translate['z'] = 'a'

然後在文件上執行單​​個傳遞,同時複製和翻譯。

#include <array> 
#include <fstream> 
#include <iostream> 
#include <numeric> 

int main() 
{ 
    std::array<char,256> translate; 
    std::iota(translate.begin(), translate.end(), 0); // identity function 

    for (;;) 
    { 
     char a, b; 
     std::cout << "\nEnter ~ to end input and translate file\n"; 
     std::cout << "What is the letter you want to swap? "; 
     std::cin >> a; 
     if (a == '~') break; 
     std::cout << "What is the letter you want to swap it with? "; 
     std::cin >> b; 
     if (b == '~') break; 
     std::swap(translate[a], translate[b]); // update translation table 
    } 

    std::ifstream infile("decrypted.txt"); 
    std::ofstream outfile("swapped.txt"); 

    if (infile && outfile) 
    { 
     std::istreambuf_iterator<char> input(infile), eof; 
     std::ostreambuf_iterator<char> output(outfile); 
     // this does the actual file copying and translation 
     std::transform(input, eof, output, [&](char c){ return translate[c]; }); 
    } 
} 
2

您已經讀取整個文件,因此不會讀取更多字節或寫入更多字節。您可以使用搜索回到開頭,或者只需關閉並重新打開文件。

+0

我已添加inFile.seekg(0);和outFile.seekp(0);但仍然不是運氣 – Dom 2011-12-15 01:33:02

+0

它可以是另一個標誌被提高除了eof?我不能看看是否會有或沒有 – Dom 2011-12-15 01:49:53

相關問題