**USING C++ IN MICROSOFT VISUAL STUDIO** The Caesar Cipher was the first documen
ID: 653165 • Letter: #
Question
**USING C++ IN MICROSOFT VISUAL STUDIO**
The Caesar Cipher was the first documented use of a substitution cipher to encode messages.
A substitution cipher substitutes each letter with a different letter. The most common implementation was the Caesar shift cipher where each letter was replaced by a letter x number of letters ahead in the alphabet.
For example, if the key (x) is 5, the word This would be replaced by YMNX. If shifting ahead passes the letter Z you wrap back around to A and continue from the beginning.It is common to print the output as all capital letters.
Write a program that first asks the user to enter the key (a number between 1 and 25). Then reads an input file input.txt, encrypts the file, as described above, using the key entered by the user, and writes the encrypted output to the file output.txt in all capital letters with one word per line.
Sample run
Enter the key: 5
input.txt
This is the input for the encryption program
output.txt
YMNX NX YMJ NSUZY KTW YMJ JSHWDUYNTS UWTLWFR
Explanation / Answer
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#define MAX 4096
void cipher(char input[], int key);
int main(){
int i, key=0;
char c, input[MAX];
FILE *file;
file = fopen("input.txt","r");
printf("Enter the key: ");
scanf("%d", &key);
getchar();
for(i=0;(c=getc(file))!=EOF && i<MAX;i++)
input[i]=c;
fclose(file);
cipher(input, key);
return 0;
}
void cipher(char input[], int key){
int length = strlen(input)-1;
int i;
char c;
FILE *file;
file = fopen("output.txt","w");
for (i=0;i<length;i++){
if (isalpha(input[i])){
c = (toupper(input[i]) - 'A'+key) % 26 + 'A';
fprintf(file, "%c", c);
}
else if (input[i]==' ')
fprintf(file, " ");
}
fclose(file);
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.