2016-02-12 112 views
-3

我寫了一個C++程序,做了一個Vigenere密碼,但我遇到了幾個C++問題。一個是該程序加密,但它不解密其加密。另一個問題是最後一個for循環是如何,它似乎並沒有正常工作。第三個問題是,c + +不會在我鍵入空間的位置添加空間。也只打印出一個字母。我真的沒有得到C++,因爲我是新手。與C++相關的問題有問題

#include <iostream> 
using namespace std; 

int main() 
{ 
    string Message;    //What The User Inputs 
    string Key;    // What Key To Go By 
    string Encryption;  // The Secret 

    cout << "\n\nEnter Your Message: "; 
    getline(cin, Message); 

    cout << "\nEnter The Main Key: "; 
    getline(cin, Key); 

    cout << "\n\n"<<endl; 


    for (int i=0; i<=Message.size(); i++) //letter i is less than the length of the message 
    { 
     int k=0; 
     Encryption[i] = (((Message[i]-97) + (Key[k]-97)) %26) + 97; //The Algorithm 
     k++; 

     if (k==Key.size()) 
     { 
      k=0; 
     } 


    } 



    for (int i=0; i<=Message.size(); i++) 
    { 
     string Result; 


     Result = Encryption[i]; 

     if (i == Message.size()) 
     { 
      cout <<"Encryption: "<< Result <<endl; 
      cout << "\n\n"<<endl; 
     } 

    } 





    return 0; 
} 

/* 
INPUT: 

Enter Your Message: Hello There 

Enter The Main Key: Secret 

OUTPUT: 

Encryption: Z 
*/ 

回答

1

點1:程序不解密加密的消息

當然它沒有。該程序不包含任何可以解密加密消息的代碼。我無法幫到第1點。

點2:最後for循環不起作用。

你不需要循環來打印出加密的消息。

cout << "Encryption: " << Encryption<< endl; 
cout << "\n\n" << endl; 

點3:

「C++是不是在哪裏我型空間增加空間」我不明白你的意思在這裏。請解釋。

點4:只有一個字符打印出來

按2點,是不是需要這個循環,而是說明了什麼問題:

for (int i=0; i<=Message.size(); i++) 
{ 
    string Result; 

創建一個名爲Result一個空的臨時字符串。每次循環結束時都會創建一個新結果,並且前一個結果將被銷燬。

Result = Encryption[i]; 

Result在字符串Encryption第i個字符。結果現在只包含一個字符。

if (i == Message.size()) 
    { 

i如果已到達消息

 cout <<"Encryption: "<< Result <<endl; 

打印的長度從一個字符在Result

 cout << "\n\n"<<endl; 
    } 
} 

另外:

沒有足夠的空間被內部string Encryption;分配。默認情況下,字符串被創建爲空。它沒有字符串長度,所以試圖索引字符串,如Encryption[i],沒有意義。沒有Encryption[i]被訪問,並試圖這樣做沒有定義的結果。它可能會導致程序崩潰。它可能看起來像是在運行,並在以後崩潰你的程序。它可以做任何事情,包括看起來像在工作。

要解決此問題,需要使用string::resize分配空間。要編碼的消息已被讀取後,

cout << "\n\nEnter Your Message: "; 
getline(cin, Message); 

添加

Encryption.resize(Message.size()); 

分配所需的存儲空間。

+0

我不明白你的意思 –

+1

@MumatAyubAli拿兩個。 – user4581301