[英]Spaces in caesar cipher in C
如果輸入不是小寫字母,則此代碼必須加密所有小寫字母並顯示錯誤消息。 如果Key
為零,則輸入將反向。
它的效果很好,但是當涉及到空間時,事情就錯了。
必須出現的內容:
plain text: notverysecure thiscaeserwas
encrypted text: jkpranuoayqna pdeoywaoanswo
出現的內容:
plain text: notverysecure thiscaeserwas
encrypted text: abgirelfrpher guvfpnrfrejnf
但是,如果輸入是:
plain text: notverysecurethiscaeserwas
encrypted text: jkpranuoayqnapdeoywaoanswo
我的猜測是Key
計算涉及空間,但是我試圖解決此問題卻無濟於事。
我的問題是如何使代碼讀取輸入中的空格,而又不讓它們參與任何形式的操縱
編碼:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
//*******************************************************************
// Function to reverse the input string
void rev (const char *const c)
{
if (*c)
{
rev (c + 1);
putchar (*c);
}
}
//*******************************************************************
int main (void)
{
char string[350];
int Key;
printf ("plain text: ");
fgets (string, sizeof (string), stdin);
Key = 256 % (strlen (string) - 1);
//***************************************************************
//ERROR CHECK
if (strlen (string) > 256)
{
printf ("[ERR] too many characters\n");
return -1;
}
for (int counter = 0; string[counter] != '\n'; counter++)
{
if ( !(islower (string[counter])) && string[counter] != ' ')
{
printf ("[ERR] invalid characters\n");
return -2;
}
//**************************************************************
int difference = 0, shift = 0;
for (int counter = 0; string[counter] != '\0'; counter++)
{
if (string[counter] >= 'a' && string[counter] <= 'z')
{
difference = 'z' - string[counter];
if (Key > difference)
{
shift = Key - (difference + 1);
string[counter] = 'a';
string[counter] += shift;
}
else
{
string[counter] += Key;
}
}
}
printf ("encrypted text: ");
if (Key == 0)
{
string[strlen(string) - 1] = '\0';
string[-1] = '\n';
rev (string);
return 0;
}
for (int counter = 0; string[counter] != '\0'; counter++)
{
printf ("%c", string[counter]);
}
}
在這種情況下,您必須在計算密鑰時手動檢查空格
int stringLength = 0;
for(int i=0;i<strlen (string);i++){
if(string[i]!=' '){
stringLength++;
}
}
Key = 256 % (stringLength - 1);
當然,在編寫代碼后, key
的計算將取決於原始字符串的長度( Key = 256 % (strlen (string) - 1);
)。與此有關的兩件事:
凱撒密碼將密鑰添加到每個已加密的char mod alphabet_size
,因此,如果您對字母進行加密,則總會得到一個字母。 這意味着Key應該在[0..alphabet_size-1]
(這不是[0..alphabet_size-1]
,但是將key添加到輸入char中的是 ,所以在這里要小心)。 在您的情況下, alphabet_size
為26,因此更好:
Key = some_value_input_from_the_user % alphabet_size;
您的密鑰取決於原始輸入字符串的字符串長度,因此,如果插入空格,則您正在更改字符串長度,因此,密鑰也會更改。 最好先詢問鍵值,或將其作為參數傳遞。 不要使事情過於復雜。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.