用戶輸入明文后發生錯誤。我對這種語言和編程本身很陌生。幫助將不勝感激。由于我在 cs50 代碼空間中作業,因此由于某種原因我無法使用除錯器,并且無法看到代碼轉儲,因為另一個問題建議我可以自己解決問題。在這里待了幾天,現在不得不發布一個問題。謝謝。
bool no_repeat(string key, int l);
string cipher(string key, string input, int l);
int main(int argc, string argv[])
{
if (argc == 2)
{
string key = argv[1];
int l = strlen(key);
int ver = 0;
for (int i = 0; i < l; i )
{
if (isalpha(key[i]))
{
ver ;
}
}
bool c = no_repeat(key, l);
if (strlen(argv[1]) == 0)
{
printf("Please enter an encryption key.\n");
return 1;
}
else if ((l != 26) || (ver != 26) || (c == false))
{
printf("Please input a correct encryption key.\n");
return 1;
}
}
else if (argc == 1)
{
printf("Please enter an encryption key.\n");
return 1;
}
string key = argv[1];
int l = strlen(key);
string input = get_string("plaintext:");
string cipherText = cipher(key, input, l);
printf("ciphertext: %s\n", cipherText);
return 0;
}
bool no_repeat(string key, int l)
{
for(int i = 0; i < l; i )
{
for (int k = i 1; k < l; k )
{
if (key[i] == key[k])
{
return false;
}
}
}
return true;
}
string cipher(string key, string input, int l)
{
string output = "";
string alphabets = "abcdefghijklmnopqrstuvwxyz";
for(int i = 0 ; i < l ; i )
{
int isUpper = isupper(key[i]);
key[i] = tolower(key[i]);
for (int k = i ; k < l ; k )
{
if (input[i] == alphabets[k])
{
output[i] = key[k];
}
else
{
output[i] = input[i];
}
}
if (isUpper != 0)
{
output[i] = toupper(output[i]);
}
}
return output;
}
uj5u.com熱心網友回復:
string可能是 a typedef char * string;,在這種情況下你不能修改string output = "";. 相反,您想用來malloc()分配一個足夠大的字串,即:
string output = malloc(strlen(input) 1);
if(!output) {
printf("malloc failed\n");
exit(1);
}
在 cipher() 中,你也在做input[i],但是i從0tostrlen(key)所以你可能會導致越界訪問。對我來說, cipher() 正在回傳密文的輸入。這是固定版本(注意,l這里和呼叫者都洗掉了引數,因為它不需要):
string cipher(string key, string input) {
string output = malloc(strlen(input) 1);
if(!output) {
printf("malloc failed\n");
exit(1);
}
const string alphabet = "abcdefghijklmnopqrstuvwxyz";
size_t j = 0;
for(size_t i = 0; i < strlen(input); i , j ) {
string pos = strchr(alphabet, tolower(input[i]));
if(!pos) {
printf("letter %c not found in alphabet\n", input[i]);
exit(1);
}
output[j] = key[pos - alphabet];
}
output[j] = '\0';
return output;
}
和示例執行:
~$ ./a.out abcdefghijklmnopqrtsuvwxzy # swap s and t
plaintext:test
ciphertext: sets
順便說一句,您不必存盤字母表,因為 ASCIIpos - alphabet中的值與tolower(input[i]) - 'a'.
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/507328.html
下一篇:不同節點的處理器之間的MPI通信
