Introduction
Caesar cipher is a simple substitution cipher where each letter in the plain text is replaced with a letter a fixed number of places down the aplhabet.
Example:
If the number of places to shift is 3, the letter A would be converted to ltter D. Using the same number of shifts the letter x wud be replaced with letter a. if we change the number of shift to 2 A wud be C and X wud be Z.
Using the shift of 3 for the plin text below
THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG.
Will result in the following cipher text
WKH TXLFN EURZQ IRA MXPSV RYHU WKH ODCB GRJ.
Problem:
IMPLEMENT A CAESAR CIPHER.
Input:
Number of shifts and the plain text. Input will terminate with negative number of shifts.
Output:
Corresponding cipher text. ONly letters will be converted. Special characters will be ignored and output will be as is.
Solution:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int ascii(char a)
{
return a;
}
int main()
{
char output[200];
int read=-1, i, k=0, key = 0, out = 0;
char *buffer = NULL;
size_t len;
while(scanf("%d", &key) && key != -1) {
/* Reset variable */
memset(&output, '', sizeof(output));
memset(&buffer, '', sizeof(buffer));
i = 0;
k = 0;
read = -1;
getchar();
read = getline(&buffer, &len, stdin);
if(-1 != read) {
while(buffer[i] != '') {
if(buffer[i] >= ascii('A') && buffer[i] <= ascii('Z')) {
out = buffer[i++] + key;
if(out > ascii('Z'))
out = out - ascii('Z') + ascii('A') - 1;
output[k++] = out;
}
else if(buffer[i] >= ascii('a') && buffer[i] <= ascii('z')) {
out = buffer[i++] + key;
if(out > ascii('z'))
out = out - ascii('z') + ascii('a') - 1;
output[k++] = out;
}
else
output[k++] = buffer[i++];
}
}
printf("Output : %s\n", output);
}
free(buffer);
return 0;
}