2012-04-04 102 views
1

我想對數組執行一些操作,最終目標是做一個簡單的加密。但無論如何,我的數組長度爲458個字符,主要由字母和一些逗號,句點等組成。我嘗試從數組的最後一個字符開始,並轉到數組中的第一個字符和大寫字母。它會正確讀取最後一個字符「」,但是for循環中的下一步就像4個字符並略過幾個字母。我的控制邏輯有問題嗎?循環邏輯,加密數組C++

void EncryptMessage (ofstream& outFile, char charArray[], int length) 
{ 
    int index; 
    char upperCased; 
    char current; 

    for (index = length-1; index <= length; --index) 
    { 
     if (charArray[index] >= 'A' && charArray[index] <= 'Z') 
     { 
      upperCased = static_cast<char>(charArray[index]); 
      current = upperCased; 
      outFile << current; 
     } 
     else 
     { 
      charArray[index]++; 
      current = charArray[index]; 
     } 

    } 
} 

回答

2

變化:

for (index = length-1; index <= length; --index) 

到:

for (index = length-1; index >= 0; --index) 
+0

這個工程,但我得到真正奇怪的輸出,這是隨機的順序,沒有一個字母是大寫的 – user1193717 2012-04-04 15:59:48

+0

沒關係問題是在else語句中,索引再次增加了一個不必要的增量。現在完美工作 – user1193717 2012-04-04 16:05:16

+1

你想只將小寫字母改爲大寫字母嗎? – hmjd 2012-04-04 16:06:01

1

else腿你if語句,你設置的current價值,但從來沒有寫出來,讓所有被寫出來是什麼的大寫字母開始(和,正如其他人指出出,你的循環條件不正確)。

如果我這樣做,我會有點不同。我會寫一個小函子來加密一個字母:

struct encrypt { 
    char operator()(char input) { 
     if (isupper(input)) 
      return input; 
     else 
      return input+1; 
    } 
}; 

然後,我把輸入到std::string,並在其上運行使用std::transform

std::string msg("content of string goes here."); 

std::transform(msg.rbegin(), msg.rend(), 
       std::ostream_iterator<char>(outFile, ""), 
       encrypt());