The .cpp code is avaiable bellow
Code:
#include <stdio.h>
#include <string.h>
int main()
{
char **kW;
char *fN;
int nW = 0;
kW = malloc(5000 * sizeof(char*));
for (int i = 0; i<5000; i++)
{
kW[i] = (char *)malloc(15);
}
fN = (char*)malloc(25);
int choice;
while (1)
{
printf("1) File text to use as cipher\n");
printf("2) Make a cipher with the input text file and save result as output file\n");
printf("3) Decode existing cipher\n");
printf("4) Exit.\n");
printf("Enter choice: ");
scanf("%d", &choice);
if (choice == 1)
{
nW = readFile(kW, fN);
}
else if (choice == 2)
{
encode(kW, fN, nW);
}
else
{
Exit();
}
printf("\n");
}
return 0;
}
int readFile(char** words, char *fN)
{
FILE *read;
printf("Enter the name of a cipher text file:");
scanf("%s", fN);
read = fopen(fN, "r");
if (read == NULL)
{
puts("Error: Couldn't open file");
fN = NULL;
return;
}
char line[1000];
int word = 0;
while (fgets(line, sizeof line, read) != NULL)
{
int i = 0;
int j = 0;
while (line[i] != '\0')
{
if (line[i] != ' ')
{
if (line[i] >= 65 && line[i] <= 90)
{
words[word][j] = line[i]; +32;
}
else
{
words[word][j] = line[i];
}
j++;
}
else
{
words[word][j] = '\n';
j = 0;
word++;
}
i++;
}
words[word][j] = '\n';
word++;
}
return word;
}
void encode(char** words, char *fN, int nwords)
{
char line[50];
char result[100];
if (strcmp(fN, "") == 0)
{
nwords = readFile(words, fN);
}
getchar();
printf("Enter a secret message(and press enter): ");
gets(line);
int i = 0, j = 0;
int w = 0, k = 0;
while (line[i] != '\0')
{
if (line[i] >= 65 && line[i] <= 90)
{
line[i] = line[i] + 32;
}
w = 0;
int found = 0;
while (w<nwords)
{
j = 0;
while (words[w][j] != '\0')
{
if (line[i] == words[w][j])
{
printf("%c -> %d,%d \n", line[i], w, j);
found = 1;
break;
}
j++;
}
if (found == 1)
break;
w++;
}
i++;
}
result[k] = '\n';
}
void Exit()
{
exit(0);
}