I am doing some basic exercises on cryptography; in one exercise I want to create two arrays, the first contains the alphabet from a to z, and for the second, I give the user the choice to form his own key alphabet. The problem I found is for example when I form the following alphabet: poiuytrezamlkjhgfdsqnbvcxw
So, I ask the user to form a sentence.. My goal is when the user forms a sentence, the letters should transform to the key alphabets he has formed. For example: The formed sentence: abyz The encrypted phrase according to your key alphabet is: poxw My problem is when I enter a sentence; the transformation always starts with the first letter of the key alphabet: "poi...". That is, the letters of the key alphabet do not exactly take the places of the original alphabet. Here is my code:
#include<stdio.h>
#include<string.h>
void main() {
char T[26]={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
char T1[26]={};
int i;
printf("We have the alphabet:\n");
puts(T);
printf("Enter your key alphabet:");
gets(T1);
printf("Your alphabet key is: ");
puts(T1);
printf("Form a phrase: ");
gets(T);
for(i=0;i<strlen(T);i++){
T[i]=T1[i];
}
printf("The encrypted phrase according to your key alphabet is: ");
puts(T);
}
Guys I found the answer after a long research. So I added another array 'userinput[]' and a variable j, I used the condition if so when I form phrase in 'userinput'[]' and this one equal 'alphabet[]'. the letters take the value of 'cipherkey[]' while guarding the positions of columns. Also I added 'for' function to i with the 'if' condition. And returned to 'j' with the 'break'.
My final code (I tried to write a clean code):
#include<stdio.h>
#include<string.h>
void main() {
char alphabet[27]={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z' };
char cipherKey[27];
char userInput[27];
printf("We have the alphabet :\n");
puts(alphabet);
printf("Enter your key alphabet: ");
gets(cipherKey);
printf("Your key alphabet is: ");
printf(cipherKey);
printf("\nForm a phrase: ");
gets(userInput);
int i;
int j;
for(j=0;j<strlen(userInput);j++){
for(i=0;i<strlen(alphabet);i++){
if(alphabet[i]==userInput[j]){
userInput[j]=cipherKey[i];
break;
}
}
}
printf("The encrypted phrase according to your key alphabet is: ");
puts(userInput);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.