/*
* simpleEncode.c
*
* reads in a permutation of the alphabet then encodes
* lower case letters using that permutation
* module 4 template code you asked for - might need some cleaning up..
*
* Created by Julian Saknussemm on 11/09/1752
* Licensed under Creative Commons BY 3.0.
*
*/
// by Sabrina Rispin
// Activity Section: 4
// Date: 28/3/15
// Description: Encodes letters based on an entered permutaion of the
// alphabet.
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#define STOP -1
#define ALPHABET_SIZE 26
#define FIRST_LC 'a'
#define LAST_LC 'z'
#define FIRST_UC 'A'
#define LAST_UC 'Z'
char encode (int plainChar, char *permuation);
void testEncode (void);
int main (int argc, char *argv[]) {
testEncode();
char permutation[ALPHABET_SIZE];
scanf ("%s", permutation);
while (strlen (permutation) != ALPHABET_SIZE) {
printf ("Please enter a string as long as the alphabet\n");
scanf ("%s", permutation);
}
// getchar() reads and returns one character from the keyboard
// returns -1 when the input is finished / end-of-file is reached
// signal this from the kayboard by pressing ^D in linux/^Z windows
int plainCharacter = getchar();
int encodedCharacter;
while (plainCharacter != STOP) {
if (plainCharacter >= FIRST_LC && plainCharacter <= LAST_LC) {
encodedCharacter = encode (plainCharacter, permutation);
} else {
encodedCharacter = plainCharacter;
}
printf ("%c", encodedCharacter);
plainCharacter = getchar();
}
return EXIT_SUCCESS;
}
void testEncode (void) {
assert (encode ('A',"abcdefghijklmnopqrstuvwxyz") == 'A');
assert (encode ('?',"abcdefghijklmnopqrstuvwxyz") == '?');
assert (encode (' ',"abcdefghijklmnopqrstuvwxyz") == ' ');
assert (encode ('\n',"abcdefghijklmnopqrstuvwxyz") == '\n');
assert (encode ('a',"abcdefghijklmnopqrstuvwxyz") == 'a');
assert (encode ('m',"abcdefghijklmnopqrstuvwxyz") == 'm');
assert (encode ('z',"abcdefghijklmnopqrstuvwxyz") == 'z');
assert (encode ('a',"bcdefghijklmnopqrstuvwxyza") == 'b');
assert (encode ('m',"bcdefghijklmnopqrstuvwxyza") == 'n');
assert (encode ('z',"bcdefghijklmnopqrstuvwxyza") == 'a');
assert (encode ('a',"qwertyuiopasdfghjklzxcvbnm") == 'q');
assert (encode ('b',"qwertyuiopasdfghjklzxcvbnm") == 'w');
assert (encode ('z',"qwertyuiopasdfghjklzxcvbnm") == 'm');
}
char encode (int plainChar, char *permuation) {
char encodedChar;
int charNum = plainChar - FIRST_LC;
if (plainChar >= FIRST_LC && plainChar <= LAST_LC) {
encodedChar = permuation[charNum];
} else {
encodedChar = plainChar;
}
return encodedChar;
}
Download file:
simpleEncode.c
(2.7 KB)