How to write a C Program Cipher in C Programming Language ?
- #include <ctype.h>
- #include <stdio.h>
- #include <stddef.h>
- #include <string.h>
- #define MAX 256
- void cipherize(char cipher[], unsigned int rotation) {
- char c;
- int ci;
- ptrdiff_t ai;
- const char alphabet[] = "abcdefghijklmnopqrstuvwxyz";
- for (ci = 0; ci < MAX; ci++) {
- if (c == '\0') break;
- c = tolower(cipher[ci]);
- if (!isalpha(c)) continue;
- ai = strchr(alphabet, c) - alphabet;
- ai += rotation;
- if (ai >= 26) ai %= 26;
- cipher[ci] = alphabet[ai];
- }
- }
- int yesorno(const char *prompt) {
- char answer;
- do {
- printf("%s (y/n): ", prompt);
- scanf(" %c", &answer);
- answer = tolower(answer);
- if (answer != 'y' && answer != 'n')
- puts("y or n.");
- } while (answer != 'y' && answer != 'n');
- return answer == 'y';
- }
- int main(void) {
- char original[MAX];
- char cipher[MAX];
- unsigned int rotation;
- /* get user input, i'm not responsible if user does it wrong */
- getcipher:
- printf("enter a cipher to attempt (max %u chars, hit enter to stop):\n", MAX - 1);
- fgets(original, MAX, stdin);
- getrotation:
- fputs("enter the rotation (1-25): ",stdout);
- scanf("%u",&rotation);
- if (rotation > 25) {
- rotation %= 25;
- printf("i said 1-25. i'm going with %u.\n", rotation);
- }
- if (rotation < 1) {
- puts("nothing to do!");
- return 0;
- }
- /* now the fun part */
- strcpy(cipher, original);
- cipherize(cipher, rotation);
- /* give output, prompt user */
- puts("translated to:");
- puts(cipher);
- if (yesorno("try another rotation?")) goto getrotation;
- if (yesorno("enter another cipher?")) goto getcipher;
- /* and we are done */
- puts("exiting...");
- return 0;
- }
Learn More :
Cipher