我将如何修改此代码以接受用户的输入而不是使用预定的字符串?具体来说,我需要程序恰好需要两个命令行参数。第一个将是代码“-e”或“-d”,表示消息的编码或解码(这决定了添加或减去您的移位值),第二个参数将是一个单词,它将是您的关键字用于加密或解密。
#include <iostream>
#include <cstring>
#include <algorithm>
// Vigenere Cipher Methods:
// Note: assumes that both strings as arguments have length > 0, and that
// the key only contains letters of the alphabet from [A-Z]
void vigenere_encrypt(std::string& s, std::string key)
{
std::transform(s.begin(), s.end(), s.begin(), ::toupper);
std::transform(key.begin(), key.end(), key.begin(), ::toupper);
unsigned int j = 0;
for (int i = 0; i < s.length(); i++)
{
if (isalpha(s[i]))
{
s[i] += key[j] - 'A';
if (s[i] > 'Z') s[i] += -'Z' + 'A' - 1;
}
j = j + 1 == key.length() ? 0 : j + 1;
}
}
void vigenere_decrypt(std::string& s, std::string key)
{
std::transform(s.begin(), s.end(), s.begin(), ::toupper);
std::transform(key.begin(), key.end(), key.begin(), ::toupper);
unsigned int j = 0;
for (int i = 0; i < s.length(); i++)
{
if (isalpha(s[i]))
{
s[i] = s[i] >= key[j] ?
s[i] - key[j] + 'A' :
'A' + ('Z' - key[j] + s[i] - 'A') + 1;
}
j = j + 1 == key.length() ? 0 : j + 1;
}
}
int main(void)
{
std::string s("AceInfinity's Example");
std::string key("Passkey");
vigenere_encrypt(s, key);
std::cout << "Encrypted: " << s << std::endl;
vigenere_decrypt(s, key);
std::cout << "Decrypted: " << s << std::endl;
return 0;
}
更新
感谢您的输入和其他一些来源,我重新开发了我的主要代码,如下所示。我无法让程序正确解密和加密字符串,我不确定错误是在代码本身的某个地方,还是操作员错误。这里有什么不寻常的地方吗?我怎样才能让这个代码能够在给定用户输入的情况下加密或解密?
#include <iostream>
#include <string>
int usage( const char* exe_name )
{
std::cerr << "Usage: " << exe_name << " -e <text to encrypt>\n"
<< " " << exe_name << " -d <text to decrypt>\n" ;
return 1 ;
}
int main( int argc, char* argv[] )
{
if (argc < 3 ) return usage( argv[0] ) ;
const std::string option = argv[1];
std::string text = argv[2];
// cat the remaining cmd line args
for( int i = 3 ; i < argc ; ++i ) { text += ' ' ; text += argv[i] ; }
const std::string key("Passkey");
if ( option== "-e" )
std::cout << "Encrypt: '" << text << "'\n" ;
else if ( option == "-d" )
std::cout << "Decrypt: '" << text << "'\n" ;
else
{
std::cout << "Unrecognised command line option '" << option << "'\n";
return usage( argv[0] ) ;
}
}