misshyde misshyde - 17 days ago 5
C Question

Mono alphabetic cipher doesnt work correctly

Here is my code. Substitution Cipher in C. But i got an error this line:

char *encryption (char cipher_text[]) {
function definition is not allowed here. I think probably "main" function place not right. How can i fix it?
And by the way how can i generate random alphabet for this code? Thank you so much.

#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <ctype.h>
#include <string.h>


char *encryption (char []);
void *decryption (char []);
char alpha [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 key[26];

int main ()
{

int i, key, choice, flag=0;
char *c_text, msg[255];
printf("\n Enter plain text:");
scanf ("%[^\n]", msg);

char *encryption (char cipher_text[]) {
int i, val, j;
printf("enter the unique KEY of 26 character:");
scanf("%s", key);
printf("\n abcdefghijklmnopqrstuvwxyz \n");
printf ("%s", key);

for (i=0; i <strlen(cipher_text); i++) {
for (j=0; j<26; j++)
{
if alpha[j]== cipher_text[i]) {
cipher_text[i]=key[j];
break;
}
}
}

printf ("your message enc: %s", cipher_text);
return cipher_text; }

}

Answer

In C, you cannot declare a function inside another function, like you did. Here is your code that will compile:

#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <ctype.h>
#include <string.h>

char *encryption (char []);
void *decryption (char []);
char alpha [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 key[26];


char *encryption (char cipher_text[]) {
int i, val, j;
printf("enter the unique KEY of 26 character:");
scanf("%s", key);
printf("\n abcdefghijklmnopqrstuvwxyz \n");
printf ("%s", key);

for (i=0; i <strlen(cipher_text); i++) 
{
    for (j=0; j<26; j++)
    {
        if (alpha[j]== cipher_text[i]) {
            cipher_text[i]=key[j];
            break;
        }
    }
}

printf ("your message enc: %s", cipher_text);
return cipher_text; 
}

int main ()
{
    int i, key, choice, flag=0;
    char *c_text, msg[255];
    printf("\n Enter plain text:");
    scanf ("%[^\n]", msg);
    encryption(msg);
    return 0;
}

How to generate random characters is answered here.