Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <cs50.h>
- #include <stdlib.h>
- #include <string.h>
- #include <ctype.h>
- int main(int argc, string argv[])
- {
- if (argc != 2)
- {
- printf("USAGE: ./caesar NUM\n");
- return 1;
- }
- //get offset value from cmdline args
- int offset=0;
- offset = atoi(argv[1]);
- for (int i=0; i<strlen(argv[1]); i++)
- {
- if (isdigit(argv[1][i]) == 0)
- {
- printf("USAGE: ./caesar NUM\n");
- return 1;
- }
- }
- //adjust for offset greater than 26 (redundant cycles)
- //eg: offset of 27 is just offset of 1. Eliminate lap of 26.
- offset = offset % 26;
- //get text to encode
- string plaintext;
- plaintext = get_string("plaintext: ");
- printf("ciphertext: ");
- int shift=0;
- //loop thru and encode each letter
- for (int i=0; i<strlen(plaintext); i++)
- {
- if (isupper(plaintext[i]) != 0)
- {
- shift = 64;
- plaintext[i] = plaintext[i] - shift; //shift letters down to 1-26
- plaintext[i] = plaintext[i] + offset; //add the caesar encryption offset
- plaintext[i] = plaintext[i] % 26; //Rotate around z to a (eg: 27 becomes 1)
- plaintext[i] = plaintext[i] + shift; //shift letters back up
- printf("%c", plaintext[i]);
- }
- else if (islower(plaintext[i]) != 0)
- {
- shift = 96;
- plaintext[i] = plaintext[i] - shift; //shift letters down to 1-26
- plaintext[i] = plaintext[i] + offset; //add the caesar encryption offset
- plaintext[i] = plaintext[i] % 26; //Rotate around z to a (eg: 27 becomes 1)
- plaintext[i] = plaintext[i] + shift; //shift letters back up
- printf("%c", plaintext[i]);
- }
- else
- {
- printf("%c", plaintext[i]);
- }
- }
- printf("\n");
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement