我正在研究基于給定密鑰進行加密的代碼。當我執行代碼時,它運行順利以檢查命令列輸入。但是,在我輸入明文后,代碼會導致“分段錯誤”。我查看了我的代碼,但不知道出了什么問題。我真的很感激任何幫助。
這是我的代碼:
#include <ctype.h>
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int encryption(string plaintext, int count_pt, int key);
int main(int argc, string argv[])
{
// Check if the program takes two arguments
if (argc != 2)
{
printf("%s", "The program takes two arguments.");
return 1;
}
// Count the characters of the second argument
int count = strlen(argv[1]);
// Make sure the second argument is digit only
for (int i = 0; i < count; i )
{
if (isdigit(argv[1][i]))
{
printf("%s\n", "Success.");
// Convert the string into integer
int key = atoi(argv[1]);
// Prompt the user for plaintext
string plaintext = get_string("Please provide the plaintext: ");
int count_pt = strlen(plaintext);
int result = encryption(plaintext, count_pt, key);
printf("%d", result);
}
else if (!isdigit(argv[1][i]))
{
printf("%s\n", "Fail.");
return 1;
}
}
}
int encryption(string plaintext, int count_pt, int key)
{
int char_array[count_pt];
int ascii_shift = 0;
//Encrypt the plaintext by wrapping the characters based on the key
for (int i = 0; i < count_pt; i )
{
//Check if characters are alphabetic
if (isalpha(plaintext))
{
if (isupper(plaintext))
{
ascii_shift = plaintext[i] - 'A';
char_array[i] = ((ascii_shift key) % 26) 'A';
}
if (islower(plaintext))
{
ascii_shift = plaintext[i] - 'a';
char_array[i] = ((ascii_shift key) % 26) 'a';
}
}
else
{
//Keep the non-alphabetical characters the same
char_array[i] = plaintext[i];
}
}
return char_array[count_pt];
}
uj5u.com熱心網友回復:
問題在于函式加密。最具體的是在這部分......
if (isalpha(plaintext))
{
if (isupper(plaintext))
{
ascii_shift = plaintext[i] - 'A';
char_array[i] = ((ascii_shift key) % 26) 'A';
}
if (islower(plaintext))
{
ascii_shift = plaintext[i] - 'a';
char_array[i] = ((ascii_shift key) % 26) 'a';
}
}
函式 isalpha()、isupper() 和 islower() 采用 int 引數,但您給它們提供明文,這是一個指標(表示記憶體地址的十六進制數)。要解決此問題,您需要傳遞明文的字符。你可以通過兩種方式做到這一點。
- 按索引訪問字符
if (isalpha(plaintext[i]))
{
if (isupper(plaintext[i]))
{
ascii_shift = plaintext[i] - 'A';
char_array[i] = ((ascii_shift key) % 26) 'A';
}
if (islower(plaintext[i]))
{
ascii_shift = plaintext[i] - 'a';
char_array[i] = ((ascii_shift key) % 26) 'a';
}
}
- 在取消參考的幫助下
if (isalpha(*plaintext))
{
if (isupper(*plaintext))
{
ascii_shift = plaintext[i] - 'A';
char_array[i] = ((ascii_shift key) % 26) 'A';
}
if (islower(*plaintext))
{
ascii_shift = plaintext[i] - 'a';
char_array[i] = ((ascii_shift key) % 26) 'a';
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/419665.html
標籤:
