In: Computer Science
Program Code Screenshot
Program Sample Console Input/Output Screenshot
out.txt after execution
Program Code to Copy
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
// create a key text work array for encryption
// we can add more characters in this for encoding
const int length=6;
char key_text[6][10]={"qwe", "rtyui", "opasd", "fghjkl", "zxcv", "bnm"};
// prompt the user to enter secret message that is terminated by presding Enter.
printf("Enter Secret Message: ");
// can assume that the the length of this message will be less than 100 characters
char buffer[100];
//take input
scanf("%[^\t\n]s",buffer);
// declare variable to store encrypted message and its counter
char message[200];
int k=0;
// parse the message character by character
int pos=0;
while(buffer[pos]!='\0'){
char x = buffer[pos];
// check for space
// Spaces are to be placed into the text as found in the message and will be used to delimit the separate words in the secret message
if(x==' '){
message[k++]=' ';
pos++;
continue;
}
int found=0;//variable to check if character if found
int i=0, j=0; //indexes to be traversed
// search this character in key text array
for(i=0;i<length;i++){
j=0;
while(key_text[i][j]!='\0' && key_text[i][j]!=x){
j++;
}
if(key_text[i][j]==x){
found=1;
break;
}
}
if(found==1){
// add index of word and character in the message
char str[100];
itoa(i, str, 100);
int cp =0;
while(str[cp!='\0']){
message[k++]=str[cp++];
}
itoa(j, str, 100);
cp =0;
while(str[cp!='\0']){
message[k++]=str[cp++];
}
}else{
printf("character %c not found in key_text array\n", x);
}
pos++;
}
message[k]='\0';
// Once the message has been encoded, prompt the user for the name of a file
char fileName[100];
printf("Enter file to save encoded message: ");
scanf("%s", fileName);
//save encoded message to this file
FILE *fp;
fp = fopen(fileName, "w+");
fprintf(fp, "%s", message);
fclose(fp);
}